-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathproxy_session.cpp
More file actions
5741 lines (4886 loc) · 145 KB
/
Copy pathproxy_session.cpp
File metadata and controls
5741 lines (4886 loc) · 145 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_session.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_session.hpp"
#include "proxy/async_connect.hpp"
#include "proxy/proxy_util.hpp"
#include "proxy/fileop.hpp"
#include <charconv>
#ifdef USE_PAM_AUTH
# include <security/pam_appl.h>
# include <security/pam_misc.h>
#endif
namespace proxy {
using io_util::read;
using io_util::write;
//////////////////////////////////////////////////////////////////////////
static const char* fake_500_content_fmt =
R"x*x*x(<html>
<head><title>500 Internal Server Error</title></head>
<body>
<center><h1>500 Internal Server Error</h1></center>
<hr><center>nginx/1.20.2</center>
</body>
</html>)x*x*x";
static const char* fake_400_content_fmt =
R"x*x*x(HTTP/1.1 400 Bad Request
Server: nginx/1.20.2
Date: {}
Content-Type: text/html
Content-Length: 165
Connection: close
<html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>nginx/1.20.2</center>
</body>
</html>)x*x*x";
static const char* fake_400_content =
R"x*x*x(<html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>nginx/1.20.2</center>
</body>
</html>)x*x*x";
static const char* fake_401_content =
R"x*x*x(<html>
<head><title>401 Authorization Required</title></head>
<body>
<center><h1>401 Authorization Required</h1></center>
<hr><center>nginx/1.20.2</center>
</body>
</html>)x*x*x";
static const char* fake_403_content =
R"x*x*x(<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.20.2</center>
</body>
</html>
)x*x*x";
static const char* fake_404_content_fmt =
R"x*x*x(HTTP/1.1 404 Not Found
Server: nginx/1.20.2
Date: {}
Content-Type: text/html
Content-Length: 145
Connection: close
<html><head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr>
<center>nginx/1.20.2</center>
</body>
</html>)x*x*x";
static const char* fake_407_content_fmt =
R"x*x*x(HTTP/1.1 407 Proxy Authentication Required
Server: nginx/1.20.2
Date: {}
Connection: close
Proxy-Authenticate: Basic realm="proxy"
Proxy-Connection: close
Content-Length: 0
)x*x*x";
static const char* fake_416_content =
R"x*x*x(<html>
<head><title>416 Requested Range Not Satisfiable</title></head>
<body>
<center><h1>416 Requested Range Not Satisfiable</h1></center>
<hr><center>nginx/1.20.2</center>
</body>
</html>
)x*x*x";
static const char* fake_302_content =
R"x*x*x(<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.20.2</center>
</body>
</html>
)x*x*x";
static constexpr auto head_fmt =
LR"(<html><head><meta charset="UTF-8"><title>Index of {}</title></head><body bgcolor="white"><h1>Index of {}</h1><hr><pre>)";
static constexpr auto tail_fmt =
L"</pre><hr></body></html>";
static constexpr auto body_fmt =
L"<a href=\"{}\">{}</a>{} {} {}\r\n";
//////////////////////////////////////////////////////////////////////////
static const std::unordered_map<std::string, std::string> global_mimes =
{
{ ".html", "text/html; charset=utf-8" },
{ ".htm", "text/html; charset=utf-8" },
{ ".js", "application/javascript" },
{ ".h", "text/javascript" },
{ ".hpp", "text/javascript" },
{ ".cpp", "text/javascript" },
{ ".cxx", "text/javascript" },
{ ".cc", "text/javascript" },
{ ".c", "text/javascript" },
{ ".json", "application/json" },
{ ".css", "text/css" },
{ ".txt", "text/plain; charset=utf-8" },
{ ".md", "text/plain; charset=utf-8" },
{ ".log", "text/plain; charset=utf-8" },
{ ".xml", "text/xml" },
{ ".ico", "image/x-icon" },
{ ".ttf", "application/x-font-ttf" },
{ ".eot", "application/vnd.ms-fontobject" },
{ ".woff", "application/x-font-woff" },
{ ".pdf", "application/pdf" },
{ ".png", "image/png" },
{ ".jpg", "image/jpg" },
{ ".jpeg", "image/jpg" },
{ ".gif", "image/gif" },
{ ".webp", "image/webp" },
{ ".svg", "image/svg+xml" },
{ ".wav", "audio/x-wav" },
{ ".ogg", "video/ogg" },
{ ".m4a", "audio/mp4" },
{ ".mp3", "audio/mpeg" },
{ ".mp4", "video/mp4" },
{ ".flv", "video/x-flv" },
{ ".f4v", "video/x-f4v" },
{ ".ts", "video/MP2T" },
{ ".mov", "video/quicktime" },
{ ".avi", "video/x-msvideo" },
{ ".wmv", "video/x-ms-wmv" },
{ ".3gp", "video/3gpp" },
{ ".mkv", "video/x-matroska" },
{ ".7z", "application/x-7z-compressed" },
{ ".ppt", "application/vnd.ms-powerpoint" },
{ ".zip", "application/zip" },
{ ".xz", "application/x-xz" },
{ ".xml", "application/xml" },
{ ".webm", "video/webm" },
{ ".weba", "audio/webm" },
{ ".m3u8", "application/vnd.apple.mpegurl" },
};
//////////////////////////////////////////////////////////////////////////
// ====================================================================
// DNS wire-format 编码/解码辅助函数 (用于 application/dns-json 支持)
// ====================================================================
// DNS 记录类型常量.
static constexpr uint16_t DNS_TYPE_A = 1;
static constexpr uint16_t DNS_TYPE_NS = 2;
static constexpr uint16_t DNS_TYPE_CNAME = 5;
static constexpr uint16_t DNS_TYPE_SOA = 6;
static constexpr uint16_t DNS_TYPE_PTR = 12;
static constexpr uint16_t DNS_TYPE_MX = 15;
static constexpr uint16_t DNS_TYPE_TXT = 16;
static constexpr uint16_t DNS_TYPE_AAAA = 28;
static constexpr uint16_t DNS_TYPE_SRV = 33;
static constexpr uint16_t DNS_TYPE_HTTPS = 65;
static constexpr uint16_t DNS_TYPE_ANY = 255;
static constexpr uint16_t DNS_TYPE_CAA = 257;
static constexpr uint16_t DNS_CLASS_IN = 1;
//////////////////////////////////////////////////////////////////////////
// http_ranges 用于保存 http range 请求头的解析结果.
// 例如: bytes=0-100,200-300,400-500
// 解析后的结果为: { {0, 100}, {200, 300}, {400, 500} }
// 例如: bytes=0-100,200-300,400-500,600
// 解析后的结果为: { {0, 100}, {200, 300}, {400, 500}, {600, -1} }
// 如果解析失败, 则返回空数组.
using http_ranges = std::vector<std::pair<int64_t, int64_t>>;
// parser_http_ranges 用于解析 http range 请求头.
static http_ranges parser_http_ranges(std::string range) noexcept
{
// 去掉前后空白.
range = strutil::remove_spaces(range);
// range 必须以 bytes= 开头, 否则返回空数组.
if (!range.starts_with("bytes="))
return {};
// 去掉开头的 bytes= 字符串 (不区分大小写).
static constexpr std::string_view bytes_prefix = "bytes=";
range.erase(0, bytes_prefix.size());
http_ranges results;
// 获取其中所有 range 字符串.
auto ranges = strutil::split(range, ",");
for (const auto& str : ranges)
{
auto r = strutil::split(std::string(str), "-");
// range 只有一个数值.
if (r.size() == 1)
{
if (str.empty())
{
results.emplace_back(0, -1);
}
else if (str.front() == '-')
{
auto pos = std::atoll(r.front().data());
results.emplace_back(-1, pos);
}
else
{
auto pos = std::atoll(r.front().data());
results.emplace_back(pos, -1);
}
continue;
}
if (r.size() == 2)
{
// range 有 start 和 end 的情况, 解析成整数到容器.
auto& start_str = r[0];
auto& end_str = r[1];
if (start_str.empty() && !end_str.empty())
{
auto end = std::atoll(end_str.data());
results.emplace_back(-1, end);
}
else
{
auto start = std::atoll(start_str.data());
auto end = std::atoll(end_str.data());
if (end_str.empty())
end = -1;
results.emplace_back(start, end);
}
continue;
}
// 在一个 range 项中不应该存在3个或以上的'-', 这属于无效的范围请求.
return {};
}
return results;
}
// 根据 range 计算文件偏移位置.
static std::tuple<int64_t, int64_t, http::status>
offset_from_range(const http_ranges& range, int64_t content_length)
{
if (range.size() != 1)
return { -1, -1, http::status::ok };
auto& r = range.front();
int64_t offset = r.first;
int64_t end = r.second;
// 起始位置为 -1, 表示从文件末尾开始读取, 例如 Range: -500
// 则表示读取文件末尾的 500 字节.
if (offset == -1)
{
// 如果第二个参数也为 -1, 则表示请求有问题, 返回 416.
if (r.second < 0)
return { offset, end, http::status::range_not_satisfiable };
// 计算起始位置和结束位置, 例如 Range: -5
// 则表示读取文件末尾的 5 字节.
// content_length - r.second 表示起始位置.
// content_length - 1 表示结束位置.
// 例如文件长度为 10 字节, 则起始位置为 5,
// 结束位置为 9(数据总长度为[0-9]), 一共 5 字节.
offset = content_length - r.second;
end = content_length - 1;
}
else if (end == -1)
{
// 起始位置为正数, 表示从文件头开始读取, 例如 Range: 500
// 则表示读取文件头的 500 字节.
if (r.first < 0)
return { offset, end, http::status::range_not_satisfiable };
offset = r.first;
end = content_length - 1;
}
if (offset == -1)
return { offset, end, http::status::ok };
return { offset, end, http::status::partial_content };
}
//////////////////////////////////////////////////////////////////////////
// proxy_session 辅助函数
enum {
PROXY_AUTH_SUCCESS = 0,
PROXY_AUTH_FAILED,
PROXY_AUTH_NONE,
PROXY_AUTH_ILLEGAL,
};
std::string proxy_session::pauth_error_message(int code) noexcept
{
switch (code)
{
case PROXY_AUTH_SUCCESS:
return "auth success";
case PROXY_AUTH_FAILED:
return "auth failed";
case PROXY_AUTH_NONE:
return "auth none";
case PROXY_AUTH_ILLEGAL:
return "auth illegal";
default:
return "auth unknown";
}
}
void proxy_session::update_bind_interface(const std::string& addr) noexcept
{
if (addr.empty())
return;
boost::system::error_code ec;
auto bind_if = net::ip::make_address(addr, ec);
if (ec)
{
// bind 地址有问题, 忽略 bind 参数, 并输出日志.
log_conn_warning()
<< ", bind address: " << addr
<< ", invalid: " << ec.message();
}
else
{
m_bind_interface = bind_if;
}
}
size_t proxy_session::connection_id() const noexcept
{
return m_connection_id;
}
bool proxy_session::is_crytpo_stream() const noexcept
{
return boost::variant2::holds_alternative<ssl_tcp_stream>(m_remote_socket);
}
//////////////////////////////////////////////////////////////////////////
// http 相关实现
net::awaitable<void> proxy_session::on_http_all_json(const http_context& hctx) noexcept
{
co_await on_http_json_impl<fs::recursive_directory_iterator>(hctx);
}
net::awaitable<void> proxy_session::on_http_json(const http_context& hctx) noexcept
{
co_await on_http_json_impl<fs::directory_iterator>(hctx);
}
std::string proxy_session::server_date_string() noexcept
{
// 缓存 date string 以避免频繁调用 time/gmtime/strftime.
// 每秒刷新一次即可满足 HTTP Date 头精度要求.
// 使用 mutex 保护静态变量, 防止多协程并发访问导致数据竞争.
static std::string cached;
static std::chrono::steady_clock::time_point last_update;
static std::mutex mtx;
auto now = std::chrono::steady_clock::now();
{
std::lock_guard<std::mutex> lock(mtx);
if (now - last_update >= std::chrono::seconds(1))
{
auto time = std::time(nullptr);
auto gmt = gmtime((const time_t*)&time);
cached.resize(64, '\0');
auto ret = strftime(cached.data(), 64, "%a, %d %b %Y %H:%M:%S GMT", gmt);
cached.resize(ret);
last_update = now;
}
return cached;
}
}
void proxy_session::user_rate_limit_config(const std::string& user) noexcept
{
// 在这里使用用户指定的速率设置替换全局速率配置.
auto found = m_option.users_rate_limit_.find(user);
if (found != m_option.users_rate_limit_.end())
{
auto& rate = *found;
m_option.tcp_rate_limit_ = rate.second;
}
}
void proxy_session::stream_expires_never(variant_stream_type& stream) noexcept
{
boost::variant2::visit([](auto& s) mutable
{
using ValueType = std::decay_t<decltype(s)>;
using NextLayerType = util::proxy_tcp_socket::next_layer_type;
if constexpr (std::same_as<NextLayerType, util::tcp_socket>)
{
if constexpr (std::same_as<util::proxy_tcp_socket, ValueType>)
{
auto& next_layer = s.next_layer();
next_layer.expires_never();
}
else if constexpr (std::same_as<util::ssl_tcp_stream, ValueType>)
{
auto& next_layer = s.next_layer().next_layer();
next_layer.expires_never();
}
}
}, stream);
}
void proxy_session::stream_expires_after(
variant_stream_type& stream, net::steady_timer::duration expiry_time) noexcept
{
if (expiry_time.count() < 0)
return;
boost::variant2::visit([expiry_time](auto& s) mutable
{
using ValueType = std::decay_t<decltype(s)>;
using NextLayerType = util::proxy_tcp_socket::next_layer_type;
if constexpr (std::same_as<NextLayerType, util::tcp_socket>)
{
if constexpr (std::same_as<util::proxy_tcp_socket, ValueType>)
{
auto& next_layer = s.next_layer();
next_layer.expires_after(expiry_time);
}
else if constexpr (std::same_as<util::ssl_tcp_stream, ValueType>)
{
auto& next_layer = s.next_layer().next_layer();
next_layer.expires_after(expiry_time);
}
}
}, stream);
}
void proxy_session::stream_rate_limit(variant_stream_type& stream, int rate) noexcept
{
boost::variant2::visit([rate](auto& s) mutable
{
using ValueType = std::decay_t<decltype(s)>;
using NextLayerType = proxy_tcp_socket::next_layer_type;
if constexpr (std::same_as<NextLayerType, tcp_socket>)
{
if constexpr (std::same_as<proxy_tcp_socket, ValueType>)
{
auto& next_layer = s.next_layer();
next_layer.rate_limit(rate);
}
else if constexpr (std::same_as<ssl_tcp_stream, ValueType>)
{
auto& next_layer = s.next_layer().next_layer();
next_layer.rate_limit(rate);
}
}
}, stream);
}
//////////////////////////////////////////////////////////////////////////
// PAM 认证
#ifdef USE_PAM_AUTH
int proxy_session::pam_conv_func(int num_msg, const struct pam_message **msg,
struct pam_response **resp, void *appdata_ptr)
{
if (num_msg <= 0 || num_msg > PAM_MAX_NUM_MSG)
return PAM_CONV_ERR;
*resp = (struct pam_response *)std::calloc(num_msg, sizeof(struct pam_response));
if (*resp == nullptr)
return PAM_BUF_ERR;
const char *password = (const char *)appdata_ptr;
for (int i = 0; i < num_msg; i++)
{
if (msg[i]->msg_style == PAM_PROMPT_ECHO_OFF)
{
(*resp)[i].resp = strdup(password);
(*resp)[i].resp_retcode = 0;
}
else
{
(*resp)[i].resp = nullptr;
}
}
return PAM_SUCCESS;
}
bool proxy_session::pam_authenticate_user(const char *service, const char *username, const char *password) noexcept
{
pam_handle_t *pamh = nullptr;
struct pam_conv conv = {
.conv = pam_conv_func,
.appdata_ptr = (void *)password // 传入密码
};
int retval = pam_start(service, username, &conv, &pamh);
if (retval != PAM_SUCCESS)
{
log_conn_warning() << ", pam_start failed: " << pam_strerror(pamh, retval);
return false;
}
retval = pam_authenticate(pamh, 0); // 核心认证
if (retval != PAM_SUCCESS) {
log_conn_warning() << ", authentication failed: " << pam_strerror(pamh, retval);
pam_end(pamh, retval);
return false;
}
retval = pam_acct_mgmt(pamh, 0); // 检查账户(如锁定、过期)
if (retval != PAM_SUCCESS) {
log_conn_warning() << ", account management failed: " << pam_strerror(pamh, retval);
pam_end(pamh, retval);
return false;
}
pam_end(pamh, PAM_SUCCESS);
log_conn_debug() << ", pam_authenticate_user success";
return true;
}
#endif // USE_PAM_AUTH
//////////////////////////////////////////////////////////////////////////
// 认证与授权
bool proxy_session::auth_required() const noexcept
{
if (!m_option.auth_users_.empty())
return true;
if (!m_option.pam_auth_.empty())
return true;
return false;
}
net::awaitable<bool> proxy_session::check_userpasswd(
const std::string& username,
const std::string& passwd, bool skip_passwd) noexcept
{
// 若不需要认证, 直接返回 true.
if (!auth_required())
co_return true;
// 检查用户名和密码是否匹配.
for (const auto& [user, pwd, addr, proxy_pass] : m_option.auth_users_)
{
if (username == user)
{
if (!skip_passwd && passwd != pwd)
continue;
user_rate_limit_config(user);
update_bind_interface(addr);
if (proxy_pass)
m_proxy_pass = proxy_pass;
co_return true;
}
}
// 如果启用了 PAM 认证, 则尝试使用 PAM 认证.
if (!skip_passwd && !m_option.pam_auth_.empty())
{
#ifdef USE_PAM_AUTH
boost::system::error_code ec;
auto result = co_await async_pam_auth(username, passwd,
m_option.pam_auth_, net_awaitable[ec]);
if (result)
{
user_rate_limit_config(username);
co_return true;
}
#endif
}
co_return false;
}
//////////////////////////////////////////////////////////////////////////
// 公共接口
void proxy_session::start() noexcept
{
auto server = m_proxy_server.lock();
if (!server)
return;
// 保存 server 的参数选项.
m_option = server->option();
// 将 local_ip 转换为 ip::address 对象, 用于后面向外发起连接时
// 绑定到指定的本地地址.
boost::system::error_code ec;
m_bind_interface = net::ip::make_address(m_option.local_ip_, ec);
if (ec)
{
// bind 地址有问题, 忽略bind参数.
m_bind_interface.reset();
}
// 如果指定了 proxy_pass_ 参数, 则记录这个参数, 在后面若用户又特指了更具体的
// proxy_pass, 则在 check_userpasswd 中更新 m_proxy_pass 为用户特定的
// proxy_pass.
m_proxy_pass = m_option.proxy_pass_;
// 保持 self 对象指针, 以防止在协程完成后 this 被销毁.
auto self = this->shared_from_this();
// 如果是透明代理, 则启动透明代理协程.
if (m_tproxy_remote)
{
net::co_spawn(m_executor,
[this, self]() -> net::awaitable<void>
{
co_await transparent_proxy();
co_return;
}, net::detached);
return;
}
// 如果是 stdio proxy, 则启动 stdio proxy 协程.
if (!m_option.stdio_target_.empty())
{
net::co_spawn(m_executor,
[this, self]() -> net::awaitable<void>
{
co_await stdio_proxy();
co_return;
}, net::detached);
return;
}
// 启动协议侦测协程.
net::co_spawn(m_executor,
[this, self]() -> net::awaitable<void>
{
if (boost::variant2::holds_alternative<proxy_tcp_socket>(m_local_socket))
{
co_await proto_detect<proxy_tcp_socket>();
}
else if (boost::variant2::holds_alternative<proxy_uds_socket>(m_local_socket))
{
co_await proto_detect<proxy_uds_socket>();
}
co_return;
}, net::detached);
}
void proxy_session::close() noexcept
{
if (m_abort)
return;
m_abort = true;
boost::system::error_code ignore_ec;
// 关闭所有 socket.
m_local_socket.close(ignore_ec);
m_remote_socket.close(ignore_ec);
}
void proxy_session::setup_tproxy(const net::ip::tcp::endpoint& tproxy_remote) noexcept
{
log_conn_debug()
<< ", tproxy setup: " << tproxy_remote;
m_tproxy_remote = tproxy_remote;
}
//////////////////////////////////////////////////////////////////////////
// 专用代理模式
net::awaitable<void> proxy_session::stdio_proxy() noexcept
{
auto executor = co_await net::this_coro::executor;
boost::system::error_code ec;
if (m_option.stdio_target_.empty())
{
log_conn_error() << ", stdio proxy requires a stdio_target";
co_return;
}
try
{
boost::system::result<url_info> expect_url;
std::string url = m_option.stdio_target_;
if (url.find("://") == std::string::npos)
url = "http://" + url;
expect_url = parse_urlinfo(url);
if (expect_url.has_error())
{
log_conn_error() << ", stdio proxy param stdio target is bad: " << url;
co_return;
}
auto [scheme, user, passwd, host, port, resource] = *expect_url;
// 查询 stdio_target_ 目标服务器的域名信息.
auto targets = co_await resolve_proxy_pass_targets();
// 创建 tcp socket 用于连接到目标服务器.
tcp::socket& remote_socket = net_tcp_socket(m_remote_socket);
// 发起连接到 stdio_target_ 目标服务器.
ec = co_await connect_proxy_pass(remote_socket, targets);
if (ec)
co_return;
// 与网关中继服务器握手.
ec = co_await proxy_pass_handshake(remote_socket,
std::string(host),
port,
*m_proxy_pass);
if (ec)
co_return;
size_t l2r_transferred = 0;
size_t r2l_transferred = 0;
#if defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
net::posix::stream_descriptor stream_stdout(m_executor, ::dup(STDOUT_FILENO));
stdio_stream stream(std::move(stream_stdout));
auto out = init_proxy_stream(std::move(stream));
auto& in = m_local_socket;
// 并发读写, 在 local 和 remote 之间互传数据.
co_await(
transfer(in, m_remote_socket, l2r_transferred)
&&
transfer(m_remote_socket, out, r2l_transferred)
);
#else
auto in_executor = boost::variant2::get<stdio_stream>(m_local_socket).get_in_executor();
auto out_executor = boost::variant2::get<stdio_stream>(m_local_socket).get_out_executor();
stdio_stream stream(in_executor, out_executor);
auto out = init_proxy_stream(std::move(stream));
auto& in = m_local_socket;
auto self = shared_from_this();
net::co_spawn(in_executor,
[this, self, &in, &l2r_transferred]() mutable -> net::awaitable<void>
{
boost::system::error_code ec;
constexpr size_t buf_size = 4096;
char buf[buf_size]{ 0 };
while (!m_abort)
{
DWORD read_bytes = 0;
read_bytes = (DWORD)co_await in.async_read_some(
net::buffer(buf, buf_size), net_awaitable[ec]);
if (ec)
break;
co_await net::async_write(
m_remote_socket,
net::buffer(buf, read_bytes),
net_awaitable[ec]);
if (ec)
break;
l2r_transferred += read_bytes;
}
co_return;
}, net::detached);
co_await net::co_spawn(out_executor,
[this, self, &out, &r2l_transferred]() mutable -> net::awaitable<void>
{
boost::system::error_code ec;
constexpr size_t buf_size = 4096;
char buf[buf_size]{ 0 };
while (!m_abort)
{
DWORD read_bytes = (DWORD)co_await m_remote_socket.async_read_some(
net::buffer(buf, buf_size), net_awaitable[ec]);
if (ec)
break;
co_await net::async_write(
out,
net::buffer(buf, read_bytes),
net_awaitable[ec]);
if (ec)
break;
r2l_transferred += read_bytes;
}
co_return;
}, net::deferred);
#endif
log_conn_debug()
<< ", transfer completed"
<< ", local to remote: "
<< l2r_transferred
<< ", remote to local: "
<< r2l_transferred;
}
catch (const std::exception& e)
{
log_conn_error() << ", stdio_proxy exception: " << e.what();
}
co_return;
}
net::awaitable<void> proxy_session::transparent_proxy() noexcept
{
auto executor = co_await net::this_coro::executor;
boost::system::error_code ec;
if (!m_proxy_pass)
{
XLOG_ERR << "transparent proxy requires a proxy_pass";
co_return;
}
try
{
tcp::socket& remote_socket = net_tcp_socket(m_remote_socket);
// 查询网关代理中继服务器域名信息.
auto targets = co_await resolve_proxy_pass_targets();
// 发起连接到网关代理中继服务器.
ec = co_await connect_proxy_pass(remote_socket, targets);
if (ec)
co_return;
// 与网关中继服务器握手.
ec = co_await proxy_pass_handshake(remote_socket,
m_tproxy_remote->address().to_string(),
m_tproxy_remote->port(),
*m_proxy_pass);
if (ec)
co_return;
co_await concurrent_transfer();
}
catch (const std::exception& e)
{
log_conn_error()
<< ", transparent_proxy exception: " << e.what();
}
co_return;
}
//////////////////////////////////////////////////////////////////////////
// 混淆与协议侦测
template
net::awaitable<bool>
proxy_session::noise_handshake<proxy_tcp_socket>(
proxy_tcp_socket& socket,
std::array<uint8_t, 16>& inkey,
std::array<uint8_t, 16>& outkey) noexcept;
template
net::awaitable<bool>
proxy_session::noise_handshake<net::local::stream_protocol::socket>(
net::local::stream_protocol::socket& socket,
std::array<uint8_t, 16>& inkey,
std::array<uint8_t, 16>& outkey) noexcept;
//////////////////////////////////////////////////////////////////////////
// 代理协议处理
net::awaitable<void> proxy_session::start_proxy() noexcept
{
// read
// +----+----------+----------+
// |VER | NMETHODS | METHODS |
// +----+----------+----------+
// | 1 | 1 | 1 to 255 |
// +----+----------+----------+
// [ ]
// or
// +----+----+----+----+----+----+----+----+----+----+....+----+
// | VN | CD | DSTPORT | DSTIP | USERID |NULL|
// +----+----+----+----+----+----+----+----+----+----+....+----+
// 1 1 2 4 variable 1
// [ ]
// 读取[]里的部分.
boost::system::error_code ec;
[[maybe_unused]] auto bytes =
co_await net::async_read(
m_local_socket,
m_local_buffer,
net::transfer_exactly(2),
net_awaitable[ec]);
if (ec)
{
log_conn_error()
<< ", read socks version: "
<< ec.message();
co_return;
}
BOOST_ASSERT(bytes == 2);
auto p = (const char*)m_local_buffer.data().data();
int socks_version = read<uint8_t>(p);
if (socks_version == SOCKS_VERSION_5)
{
if (m_option.disable_socks_)
{
log_conn_debug()
<< ", socks5 protocol disabled";
co_return;
}
log_conn_debug()