forked from liulilittle/openppp2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.cpp
1732 lines (1515 loc) · 65.9 KB
/
main.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
#include <ppp/configurations/AppConfiguration.h>
#include <ppp/Int128.h>
#include <ppp/io/File.h>
#include <ppp/tap/ITap.h>
#include <ppp/net/Ipep.h>
#include <ppp/net/IPEndPoint.h>
#include <ppp/auxiliary/StringAuxiliary.h>
#include <ppp/diagnostics/Stopwatch.h>
#include <ppp/diagnostics/PreventReturn.h>
#include <ppp/threading/Timer.h>
#include <ppp/threading/Thread.h>
#include <ppp/threading/Executors.h>
#include <ppp/threading/BufferswapAllocator.h>
#include <ppp/app/server/VirtualEthernetSwitcher.h>
#include <ppp/app/server/VirtualEthernetManagedServer.h>
#include <ppp/app/client/VEthernetExchanger.h>
#include <ppp/app/client/VEthernetNetworkSwitcher.h>
#if defined(_WIN32)
#include <windows/ppp/net/proxies/HttpProxy.h>
#include <windows/ppp/tap/TapWindows.h>
#include <windows/ppp/win32/Win32Native.h>
#include <windows/ppp/win32/network/Firewall.h>
#include <windows/ppp/win32/network/NetworkInterface.h>
#else
#include <common/unix/UnixAfx.h>
#if defined(_MACOS)
#include <darwin/ppp/tap/TapDarwin.h>
#else
#include <linux/ppp/tap/TapLinux.h>
#include <linux/ppp/diagnostics/UnixStackTrace.h>
#endif
#endif
#if defined(CURLINC_CURL)
#include <curl/curl.h>
#endif
#include <openssl/opensslv.h>
#include <openssl/evp.h>
#include <openssl/aes.h>
#include <openssl/rand.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <common/chnroutes2/chnroutes2.h>
using ppp::configurations::AppConfiguration;
using ppp::threading::Executors;
using ppp::threading::Thread;
using ppp::threading::Timer;
using ppp::threading::BufferswapAllocator;
using ppp::diagnostics::Stopwatch;
using ppp::diagnostics::PreventReturn;
using ppp::tap::ITap;
using ppp::net::Ipep;
using ppp::net::IPEndPoint;
using ppp::net::AddressFamily;
using ppp::net::Socket;
using ppp::io::File;
using ppp::io::FileAccess;
using ppp::auxiliary::StringAuxiliary;
using ppp::app::server::VirtualEthernetSwitcher;
using ppp::app::client::VEthernetNetworkSwitcher;
using ppp::app::client::VEthernetExchanger;
using ppp::app::client::proxys::VEthernetLocalProxySwitcher;
using ppp::app::client::proxys::VEthernetHttpProxySwitcher;
using ppp::app::client::proxys::VEthernetSocksProxySwitcher;
using ppp::Int128;
struct NetworkInterface final
{
#if defined(_WIN32)
uint32_t LeaseTimeInSeconds = 0;
bool SetHttpProxy = false;
#else
bool Promisc = false;
int Ssmt = 0;
#if defined(_LINUX)
bool SsmtMQ = false;
bool ProtectNetwork = false;
#endif
#endif
bool StaticMode = false;
bool Lwip = false;
bool VNet = false;
bool HostedNetwork = false;
bool BlockQUIC = false;
ppp::string BypassIplist;
ppp::string ComponentId;
ppp::string FirewallRules;
ppp::string DNSRules;
ppp::string Nic;
ppp::vector<boost::asio::ip::address> DnsAddresses;
boost::asio::ip::address Ngw;
boost::asio::ip::address IPAddress;
boost::asio::ip::address GatewayServer;
boost::asio::ip::address SubmaskAddress;
};
struct ConsoleForegroundWindowSize final
{
int x = -1;
int y = -1;
};
class PrintToConsoleForegroundWindow final
{
public:
ConsoleForegroundWindowSize* console_window_size = NULL;
ppp::string* console_window_content = NULL;
int* console_window_heights = NULL;
public:
template <class... A>
void operator()(const char* format, A&&... args) noexcept
{
// Control the number of lines that need to be printed to the console window to prevent crowding the visible display area
// Of the console window, and when the console window size changes, follow the printed content until it is fully printed.
if (console_window_size->y > *console_window_heights)
{
ppp::string st = PrintToString(console_window_size->x, ' ', format, std::forward<A&&>(args)...);
(*console_window_heights)++;
console_window_content->append(st);
}
}
public:
template <class... A>
ppp::string PrintToString(std::size_t padding_length, char padding_char, const char* format, A&&... args) noexcept
{
char buf[8096];
snprintf(buf, sizeof(buf), format, std::forward<A&&>(args)...);
return ppp::PaddingRight<ppp::string>(buf, padding_length, padding_char);
}
};
class PppApplication
{
public:
PppApplication() noexcept;
virtual ~PppApplication() noexcept;
public:
int Main(int argc, const char* argv[]) noexcept;
void Dispose() noexcept;
public:
static std::shared_ptr<PppApplication> GetDefault() noexcept;
static bool AddShutdownApplicationEventHandler() noexcept;
public:
std::shared_ptr<AppConfiguration> GetConfiguration() noexcept;
std::shared_ptr<VirtualEthernetSwitcher> GetServer() noexcept;
std::shared_ptr<VEthernetNetworkSwitcher> GetClient() noexcept;
std::shared_ptr<BufferswapAllocator> GetBufferAllocator() noexcept;
public:
void PrintHelpInformation() noexcept;
void PullIPList(const ppp::string& command) noexcept;
int PreparedArgumentEnvironment(int argc, const char* argv[]) noexcept;
protected:
virtual bool OnTick(uint64_t now) noexcept;
private:
std::shared_ptr<AppConfiguration> LoadConfiguration(int argc, const char* argv[], ppp::string& path) noexcept;
bool IsModeClientOrServer(int argc, const char* argv[]) noexcept;
std::shared_ptr<NetworkInterface> GetNetworkInterface(int argc, const char* argv[]) noexcept;
boost::asio::ip::address GetNetworkAddress(const char* name, int MIN_PREFIX_ADDRESS, int MAX_PREFIX_ADDRESS, int argc, const char* argv[]) noexcept;
boost::asio::ip::address GetNetworkAddress(const char* name, int MIN_PREFIX_ADDRESS, int MAX_PREFIX_ADDRESS, const char* default_address_string, int argc, const char* argv[]) noexcept;
void GetDnsAddresses(ppp::vector<boost::asio::ip::address>& addresses, int argc, const char* argv[]) noexcept;
bool PreparedLoopbackEnvironment(const std::shared_ptr<NetworkInterface>& network_interface) noexcept;
bool PrintEnvironmentInformation() noexcept;
private:
static bool NextTickAlwaysTimeout(bool next) noexcept;
void ClearTickAlwaysTimeout() noexcept;
private:
bool GetTransmissionStatistics(uint64_t& incoming_traffic, uint64_t& outgoing_traffic, std::shared_ptr<ppp::transmissions::ITransmissionStatistics>& statistics_snapshot) noexcept;
private:
ConsoleForegroundWindowSize console_window_size_last_;
bool client_mode_ = false;
bool quic_ = false;
std::shared_ptr<AppConfiguration> configuration_;
std::shared_ptr<VirtualEthernetSwitcher> server_;
std::shared_ptr<VEthernetNetworkSwitcher> client_;
ppp::string configuration_path_;
std::shared_ptr<NetworkInterface> network_interface_;
std::shared_ptr<Timer> timeout_ = 0;
Stopwatch stopwatch_;
PreventReturn prevent_rerun_;
ppp::transmissions::ITransmissionStatistics transmission_statistics_;
};
static std::shared_ptr<PppApplication> PPP_APPLICATION_DEFAULT_APP_DOMAIN;
PppApplication::PppApplication() noexcept
{
// Hide the cursor that is currently flashing on the console.
ppp::HideConsoleCursor(true);
#if defined(_WIN32)
// Set the title information for the current user-facing console window!
SetConsoleTitle(TEXT("PPP PRIVATE NETWORK™ 2"));
// Set the default matrix size for the console window, valid only on Windows platforms.
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
if (NULL != hConsole)
{
COORD cSize = { 120, 45 }; /* ppp::win32::Win32Native::IsWindows11OrLaterVersion(); */
if (SetConsoleScreenBufferSize(hConsole, cSize))
{
SMALL_RECT rSize = { 0, 0, cSize.X - 1, cSize.Y - 1 };
SetConsoleWindowInfo(hConsole, TRUE, &rSize);
}
}
// Hide the close button of the console window to prevent users from illegally forcing the VPN program to close.
ppp::win32::Win32Native::EnabledConsoleWindowClosedButton(false);
#endif
}
PppApplication::~PppApplication() noexcept
{
// Display the cursor that is currently flashing on the console.
ppp::HideConsoleCursor(false);
#if defined(_WIN32)
// Display the close button of the console window, otherwise the host console window close button cannot be clicked.
ppp::win32::Win32Native::EnabledConsoleWindowClosedButton(true);
#endif
// Turn off the global named mutex lock that prevents programs from running repeatedly!
prevent_rerun_.Close();
}
void PppApplication::PullIPList(const ppp::string& command) noexcept
{
// Notify the customer that the IPlist is being pulled from the APNIC.
time_t last = chnroutes2_gettime();
fprintf(stdout, "[%s]PULL\r\n", chnroutes2_gettime(last).data());
// Gets ip address list and nation parameters passed into the command-line.
ppp::string path;
ppp::string nation;
for (ppp::string command_string = ppp::LTrim(ppp::RTrim(command)); command_string.size() > 0;)
{
std::size_t index = command_string.find('<');
if (index == std::string::npos)
{
index = command_string.find('/');
if (index == std::string::npos)
{
path = command_string;
break;
}
}
path = ppp::RTrim(command_string.substr(0, index));
nation = ppp::LTrim(command_string.substr(index + 1));
break;
}
// If no path is passed to save the IP list file, the default storage path is automatically obtained.
if (path.empty())
{
path = chnroutes2_filepath_default();
}
// Getting the latest IPlist routing table information from APNIC, synchronized execution will block the main thread.
bool ok = false;
ppp::set<ppp::string> ips;
if (chnroutes2_getiplist(ips, nation) > 0)
{
ok = chnroutes2_saveiplist(path, ips);
}
// Reports the current status of the IPlist pulled from the APNIC.
time_t now = chnroutes2_gettime();
if (ok)
{
fprintf(stdout, "[%s]OK\r\n", chnroutes2_gettime(now).data());
}
else
{
fprintf(stdout, "[%s]FAIL\r\n", chnroutes2_gettime(now).data());
}
}
bool PppApplication::PrintEnvironmentInformation() noexcept
{
// Check if the network interface information for the current app exists and is valid, otherwise return failure.
std::shared_ptr<NetworkInterface> network_interface = network_interface_;
if (NULL == network_interface)
{
return false;
}
// Move the current console cursor position to the initial position and re-render the console output.
if (!ppp::SetConsoleCursorPosition(0, 0))
{
return false;
}
// Retrieve the current hosting environment, which essentially distinguishes between the debug and release versions, but it doesn't have significant meaning.
ppp::string hosting_environment;
#if defined(_DEBUG)
hosting_environment = "development";
#else
hosting_environment = "production";
#endif
std::shared_ptr<VEthernetNetworkSwitcher> client = client_;
hosting_environment = (NULL != client ? "client:" : "server:") + hosting_environment;
// Get the size of the console window.
ConsoleForegroundWindowSize console_window_size;
if (!ppp::GetConsoleWindowSize(console_window_size.x, console_window_size.y))
{
return false;
}
// If the size of the current console window changes, clear the output content of the console window.
if (console_window_size_last_.x != console_window_size.x || console_window_size_last_.y != console_window_size.y)
{
console_window_size_last_
= console_window_size;
ppp::ClearConsoleOutputCharacter();
}
// Define an anonymous arrow function that prints and newline with a locally variable argument list.
ppp::string console_window_content;
int console_window_heights = 0;
PrintToConsoleForegroundWindow printfn = { &console_window_size, &console_window_content, &console_window_heights };
// Get the separator symbol for console tabs.
ppp::string section_separator;
section_separator = ppp::PaddingRight(section_separator, console_window_size.x, '-');
// Printing ready-to-start VPN client or server program log informations.
printfn("%s", PPP_APPLICATION_NAME);
printfn("%s", section_separator.data());
printfn("%s", "Application started. Press Ctrl+C to shut down.");
printfn("Max Concurrent : %d", configuration_->concurrent);
printfn("Process : %d", ppp::GetCurrentProcessId());
printfn("Triplet : %s:%s", ppp::GetSystemCode(), ppp::GetPlatformCode());
printfn("Cwd : %s", ppp::GetCurrentDirectoryPath().data());
printfn("Template : %s", configuration_path_.data());
// Print some information about the server's Virtual Ethernet switcher.
std::shared_ptr<VirtualEthernetSwitcher> server = server_;
if (NULL != server)
{
// Displays the link status and link Uri of the VPN back-end management server.
auto managed_server = server->GetManagedServer();
if (NULL != managed_server)
{
const char* link_state = "connecting";
if (managed_server->LinkIsAvailable()) {
link_state = "established";
}
elif(managed_server->LinkIsReconnecting()) {
link_state = "reconnecting";
}
ppp::string link_url = managed_server->GetUri();
printfn("Managed Server : %s @(%s)", link_url.data(), link_state);
}
}
// Print some information about the client's Virtual Ethernet switcher.
if (NULL != client)
{
// Print the address of the remote server currently in use by the client!
if (ppp::string remote_uri = client->GetRemoteUri(); remote_uri.size() > 0)
{
std::shared_ptr<VEthernetExchanger> exchanger = client->GetExchanger();
printfn("VPN Server : %s [%s]", remote_uri.data(), NULL != exchanger && exchanger->StaticEchoAllocated() ? "static" : "dynamic");
}
// Print the information related to the http/socks proxy server tab.
struct
{
const char* proxy;
std::shared_ptr<VEthernetLocalProxySwitcher> switcher;
} proxys[] =
{
{ "Http Proxy : %s/http", client->GetHttpProxy() },
{ "Socks Proxy : %s/socks", client->GetSocksProxy() }
};
for (auto& st : proxys)
{
std::shared_ptr<VEthernetLocalProxySwitcher> switcher = st.switcher;
if (NULL == switcher)
{
continue;
}
boost::asio::ip::tcp::endpoint localEP = switcher->GetLocalEndPoint();
boost::asio::ip::address localIP = localEP.address();
if (localIP.is_unspecified())
{
if (auto ni = client->GetUnderlyingNetowrkInterface(); NULL != ni)
{
localIP = ni->IPAddress;
}
}
// Displays the address of the http/socks proxy server for the local virtual loopback.
ppp::string address_string = IPEndPoint::ToEndPoint(boost::asio::ip::tcp::endpoint(localIP, localEP.port())).ToString();
printfn(st.proxy, address_string.data());
}
#if defined(_WIN32)
// Displays the open status of the current paper Airplane session layer plugins.
printfn("P/A Controller : %s", client->GetPaperAirplaneController() ? "on" : "off");
#endif
}
// Print some display information of the current virtual ethernet server!
if (std::shared_ptr<VirtualEthernetSwitcher> server = server_; NULL != server)
{
using NAC = VirtualEthernetSwitcher::NetworkAcceptorCategories;
// Print the public IP address and interface IP address configured for the current virtual Ethernet server!
if (std::shared_ptr<AppConfiguration> configuration = configuration_; NULL != configuration)
{
printfn("Public IP : %s", configuration->ip.public_.data());
printfn("Interface IP : %s", configuration->ip.interface_.data());
}
// Displays the port numbers of various server public service addresses that are currently monitored.
const char* categories[] = { "ppp+tcp", "ppp+udp", "ppp+ws", "ppp+wss", "cdn+1", "cdn+2" };
VirtualEthernetSwitcher::NetworkAcceptorCategories categoriess[] =
{
NAC::NetworkAcceptorCategories_Tcpip,
NAC::NetworkAcceptorCategories_Udpip,
NAC::NetworkAcceptorCategories_WebSocket,
NAC::NetworkAcceptorCategories_WebSocketSSL,
NAC::NetworkAcceptorCategories_CDN1,
NAC::NetworkAcceptorCategories_CDN2,
};
for (int i = 0, j = 0; i < arraysizeof(categories); i++)
{
boost::asio::ip::tcp::endpoint serverEP = server->GetLocalEndPoint(categoriess[i]);
if (serverEP.port() <= IPEndPoint::MinPort || serverEP.port() > IPEndPoint::MaxPort)
{
continue;
}
ppp::string tmp = "Service ";
tmp += stl::to_string<ppp::string>(++j);
tmp = ppp::PaddingRight(tmp, 22, ' ');
tmp += ": " + IPEndPoint::ToEndPoint(serverEP).ToString();
tmp += "/";
tmp += categories[i];
printfn("%s", tmp.data());
}
}
// Displays the current host environment type, in effect marking whether it is a released product or a development debug release.
printfn("Hosting Environment : %s", hosting_environment.data());
// To print a blank line as a separator for major categories.
printfn("");
// Displays information about the bearer network interface used by the VPN.
if (NULL != client)
{
// Print all display information related to TAP tabs one by one.
struct
{
std::shared_ptr<VEthernetNetworkSwitcher::NetworkInterface> ni;
const char* tab;
bool tun;
} stnis[] = {
{ client->GetTapNetworkInterface(), "TUN", true, },
{ client->GetUnderlyingNetowrkInterface(), "NIC", false },
};
for (auto&& sti : stnis)
{
auto ni = sti.ni;
if (NULL != ni)
{
printfn("%s", sti.tab);
printfn("%s", section_separator.data());
#if defined(_WIN32)
printfn("Name : %s[%s]", ni->Name.data(), ni->Description.data());
#else
printfn("Name : %s", ni->Name.data());
#endif
printfn("Index : %d", ni->Index);
#if !defined(_MACOS)
ppp::string component_id = ni->Id;
if (component_id.size() > 0)
{
printfn("Id : %s", component_id.data());
}
#endif
printfn("Interface : %s %s %s",
ni->IPAddress.to_string().data(),
ni->GatewayServer.to_string().data(),
ni->SubmaskAddress.to_string().data());
if (sti.tun)
{
for (const char* aggligator_status[] = { "none", "unknown", "connecting", "reconnecting", "established" };;)
{
if (std::shared_ptr<aggligator::aggligator> aggligator = client->GetAggligator(); NULL != aggligator)
{
aggligator::aggligator::link_status link_status = aggligator->status();
printfn("Aggligator : %s", aggligator_status[(int)link_status]);
}
else
{
printfn("Aggligator : %s", *aggligator_status);
}
break;
}
for (std::shared_ptr<ppp::transmissions::proxys::IForwarding> forwarding = client->GetForwarding();;)
{
if (NULL != forwarding)
{
ppp::string proxy_url = forwarding->GetProxyUrl();
printfn("Proxy Interlayer : %s", proxy_url.data());
}
else
{
printfn("Proxy Interlayer : %s", "none");
}
break;
}
printfn("TCP/IP CC : %s", client->IsLwip() ? "lwip" : "ctcp");
printfn("Block QUIC : %s", client->IsBlockQUIC() ? "blocked" : "unblocked");
if (std::shared_ptr<VEthernetExchanger> exchanger = client->GetExchanger(); NULL != exchanger)
{
const char* network_states[] = { "connecting", "established", "reconnecting" };
printfn("Link State : %s", network_states[(int)exchanger->GetNetworkState()]);
}
else
{
printfn("Link State : %s", "none");
}
}
for (std::size_t i = 0, l = ni->DnsAddresses.size(); i < l; i++)
{
ppp::string tmp = "DNS Server " + stl::to_string<ppp::string>(i + 1);
tmp = ppp::PaddingRight(tmp, 22, ' ');
tmp += ": " + ni->DnsAddresses[i].to_string();
printfn("%s", tmp.data());
}
// To print a blank line as a separator for major categories.
printfn("");
}
}
}
// Get statistics on the physical network transport layer of the Virtual Ethernet switcher.
struct
{
uint64_t incoming_traffic;
uint64_t outgoing_traffic;
std::shared_ptr<ppp::transmissions::ITransmissionStatistics> statistics_snapshot;
} TransmissionStatistics;
if (!GetTransmissionStatistics(TransmissionStatistics.incoming_traffic, TransmissionStatistics.outgoing_traffic, TransmissionStatistics.statistics_snapshot))
{
TransmissionStatistics.incoming_traffic = 0;
TransmissionStatistics.outgoing_traffic = 0;
TransmissionStatistics.statistics_snapshot = NULL;
}
// Implement some information printing on the console window for VPN information.
printfn("%s", "VPN");
printfn("%s", section_separator.data());
printfn("Duration : %s", stopwatch_.Elapsed().ToString("TT:mm:ss", false).data());
if (NULL != server)
{
printfn("Sessions : %s", stl::to_string<ppp::string>(server->GetAllExchangerNumber()).data());
}
printfn("TX : %s", ppp::StrFormatByteSize(TransmissionStatistics.outgoing_traffic).data());
printfn("RX : %s", ppp::StrFormatByteSize(TransmissionStatistics.incoming_traffic).data());
if (auto statistics = TransmissionStatistics.statistics_snapshot; statistics)
{
printfn("IN : %s", ppp::StrFormatByteSize(statistics->IncomingTraffic).data());
printfn("OUT : %s", ppp::StrFormatByteSize(statistics->OutgoingTraffic).data());
}
// Print text to the console window screen, or on Linux to the _tty of the shell-terminal.
fprintf(stdout, "%s", console_window_content.data());
return true;
}
bool PppApplication::PreparedLoopbackEnvironment(const std::shared_ptr<NetworkInterface>& network_interface) noexcept
{
std::shared_ptr<AppConfiguration> configuration = GetConfiguration();
if (NULL == configuration)
{
return false;
}
std::shared_ptr<boost::asio::io_context> context = Executors::GetDefault();
if (NULL == context)
{
return false;
}
else
{
#if defined(_WIN32)
// The system32 firewall Settings are automatically deployed and set in the os,
// Because overlapping io requires its support, otherwise it cannot be used.
ppp::string executable_path = File::GetFullPath(File::RewritePath(ppp::GetFullExecutionFilePath().data()).data());
// Compatibility failure: In some LTSB versions of Windows operating systems, the kernel firewall may not be initialized,
// Resulting in openppp2 having no way to configure the kernel firewall rules in this scenario.
ppp::win32::network::Fw::NetFirewallAddApplication(PPP_APPLICATION_NAME, executable_path.data());
ppp::win32::network::Fw::NetFirewallAddAllApplication(PPP_APPLICATION_NAME, executable_path.data());
// There are some basic transactions that need to be configured in the operating system before running openppp2 client mode.
if (client_mode_)
{
// If the configuration file specifies that the paper plane needs to be pulled up,
// The initialization actions associated with the paper plane are performed.
if (network_interface->HostedNetwork && configuration->client.paper_airplane.tcp)
{
// Try to install or update the paper airplane plugin into the operating system.
if (ppp::app::client::lsp::PaperAirplaneController::Install() < 0)
{
return false;
}
}
// Prohibit some system programs from loading LSPS /DLLs plug-ins because these programs may cause problems.
// The solution is to completely prohibit these programs from loading LSP/s.
ppp::app::client::lsp::PaperAirplaneController::NoLsp();
// Reset the paper plane controller Settings because the program may have closed abnormally,
// Which may cause the paper plane controller to not close properly.
ppp::app::client::lsp::PaperAirplaneController::Reset();
}
#endif
}
bool success = false;
if (client_mode_)
{
std::shared_ptr<VEthernetNetworkSwitcher> ethernet = NULL;
std::shared_ptr<ITap> tap = NULL;
do
{
// Try to open the tun/tap virtual Ethernet device!
#if defined(_WIN32)
tap = ITap::Create(context,
network_interface->ComponentId,
Ipep::ToAddressString<ppp::string>(network_interface->IPAddress),
Ipep::ToAddressString<ppp::string>(network_interface->GatewayServer),
Ipep::ToAddressString<ppp::string>(network_interface->SubmaskAddress),
network_interface->LeaseTimeInSeconds,
network_interface->HostedNetwork,
Ipep::AddressesTransformToStrings(network_interface->DnsAddresses));
#else
tap = ITap::Create(context,
network_interface->ComponentId,
Ipep::ToAddressString<ppp::string>(network_interface->IPAddress),
Ipep::ToAddressString<ppp::string>(network_interface->GatewayServer),
Ipep::ToAddressString<ppp::string>(network_interface->SubmaskAddress),
network_interface->Promisc,
network_interface->HostedNetwork,
Ipep::AddressesTransformToStrings(network_interface->DnsAddresses));
#endif
if (NULL == tap)
{
fprintf(stdout, "%s\r\n", "Open tun/tap driver failure.");
break;
}
else
{
fprintf(stdout, "%s\r\n", "Open tun/tap driver success.");
}
// Gets the current buffer allocator and sets it to tun/tap.
tap->BufferAllocator = configuration->GetBufferAllocator();
if (!tap->Open())
{
fprintf(stdout, "%s\r\n", "Listen tun/tap driver failure.");
break;
}
else
{
fprintf(stdout, "%s\r\n", "Listen tun/tap driver success.");
}
// Construct the switcher instance after creating the virtual ethernet network switcher object in client mode
// And adding the iplist file to load to bypass the vpn route.
ethernet = ppp::make_shared_object<VEthernetNetworkSwitcher>(context, network_interface->Lwip, network_interface->VNet, configuration->concurrent > 1, configuration);
if (NULL == ethernet)
{
break;
}
#if !defined(_WIN32)
// Ssmt technology squeezes the machine performance of the device as much as possible for VPN VEthernet services.
ethernet->Ssmt(&network_interface->Ssmt);
#if defined(_LINUX)
ethernet->SsmtMQ(&network_interface->SsmtMQ);
ethernet->ProtectMode(&network_interface->ProtectNetwork);
#endif
#endif
ethernet->StaticMode(&network_interface->StaticMode);
ethernet->PreferredNgw(network_interface->Ngw);
ethernet->PreferredNic(network_interface->Nic);
ethernet->AddLoadIPList(network_interface->BypassIplist);
ethernet->LoadAllDnsRules(network_interface->DNSRules, true);
if (!ethernet->Open(tap))
{
auto ni = ethernet->GetUnderlyingNetowrkInterface();
if (NULL != ni)
{
fprintf(stdout, "%s\r\n", "Failed to open the vpn client.");
}
else
{
fprintf(stdout, "%s\r\n", "No available nic could be found.");
}
break;
}
success = true;
client_ = ethernet;
} while (false);
// When the creation of a virtual Ethernet switch fails, it is important to close and reclaim any unnecessary managed resources.
if (!success)
{
client_.reset();
if (NULL != ethernet)
{
ethernet->Dispose();
}
// Turn off the tun/tap virtual network card driver that has been opened.
if (NULL != tap)
{
tap->Dispose();
}
}
}
else
{
std::shared_ptr<VirtualEthernetSwitcher> ethernet = NULL;
do
{
// Instantiate and open a vpn virtual ethernet network switcher object in server-mode.
ethernet = ppp::make_shared_object<VirtualEthernetSwitcher>(configuration);
if (NULL == ethernet)
{
break;
}
if (!ethernet->Open(network_interface->FirewallRules))
{
fprintf(stdout, "%s\r\n", "Failed to open the vpn server.");
break;
}
// Run all externally provided services of the switcher object that have just been instantiated and opened.
if (!ethernet->Run())
{
fprintf(stdout, "%s\r\n", "Listen to vpn server failure.");
break;
}
success = true;
server_ = ethernet;
} while (false);
// When the creation of a virtual Ethernet switch fails, it is important to close and reclaim any unnecessary managed resources.
if (!success)
{
server_.reset();
if (NULL != ethernet)
{
ethernet->Dispose();
}
}
}
return success;
}
std::shared_ptr<BufferswapAllocator> PppApplication::GetBufferAllocator() noexcept
{
std::shared_ptr<AppConfiguration> configuration = GetConfiguration();
if (NULL == configuration)
{
return NULL;
}
else
{
return configuration->GetBufferAllocator();
}
}
int PppApplication::PreparedArgumentEnvironment(int argc, const char* argv[]) noexcept
{
// Check whether the network mode is set to flash.
Socket::SetDefaultFlashTypeOfService(ppp::ToBoolean(ppp::GetCommandArgument("--tun-flash", argc, argv).data()));
if (ppp::IsInputHelpCommand(argc, argv))
{
return -1;
}
ppp::string path;
std::shared_ptr<AppConfiguration> configuration = LoadConfiguration(argc, argv, path);
if (NULL == configuration)
{
return -1;
}
else
{
// Gets whether client mode or server mode is currently running.
client_mode_ = IsModeClientOrServer(argc, argv);
}
int max_concurrent = configuration->concurrent - 1;
if (max_concurrent > 0)
{
Executors::SetMaxSchedulers(max_concurrent);
if (!client_mode_)
{
Executors::SetMaxThreads(configuration->GetBufferAllocator(), max_concurrent);
}
}
std::shared_ptr<NetworkInterface> network_interface = GetNetworkInterface(argc, argv);
if (NULL == network_interface)
{
return -1;
}
configuration_path_ = path;
configuration_ = configuration;
network_interface_ = network_interface;
return 0;
}
static ppp::string GetVersionString(int major, int minor, int patch = 0) noexcept
{
char buf[100];
*buf = '\x0';
if (patch != 0)
{
snprintf(buf, sizeof(buf), "%d.%d.%d", major, minor, patch);
}
else
{
snprintf(buf, sizeof(buf), "%d.%d", major, minor);
}
return buf;
}
static ppp::string GetBoostVersionString() noexcept
{
constexpr int version = BOOST_VERSION;
int minor = (version / 100) % 100;
int major = version / 100000;
int patch = version % 100;
return GetVersionString(major, minor, patch);
}
void PppApplication::PrintHelpInformation() noexcept
{
ppp::string execution_file_name = ppp::GetExecutionFileName();
ppp::string messages = "Copyright (C) 2017 ~ 2035 SupersocksR ORG. All rights reserved.\r\n";
messages += "Ppp-2(X) %s Version\r\n";
messages += "Cwd:\r\n " + ppp::GetCurrentDirectoryPath() + "\r\n";
messages += "Usage:\r\n ./%s \\\r\n";
messages += " --mode=[client|server] \\\r\n";
messages += " --config=[./appsettings.json] \\\r\n";
messages += " --lwip=[yes|no] \\\r\n";
messages += " --nic=[en0] \\\r\n";
messages += " --ngw=[0.0.0.0] \\\r\n";
messages += " --tun=[%s] \\\r\n";
messages += " --tun-ip=[10.0.0.2] \\\r\n";
#if defined(_WIN32)
messages += " --tun-gw=[10.0.0.0] \\\r\n";
#else
messages += " --tun-gw=[10.0.0.1] \\\r\n";
#endif
messages += " --tun-mask=[30] \\\r\n";
messages += " --tun-vnet=[yes|no] \\\r\n";
messages += " --tun-host=[yes|no] \\\r\n";
messages += " --tun-flash=[yes|no] \\\r\n";
messages += " --tun-static=[yes|no] \\\r\n";
#if defined(_WIN32)
messages += " --tun-lease-time-in-seconds=[7200] \\\r\n";
#else
#if defined(_LINUX)
messages += " --tun-ssmt=[[4]/[mq]] \\\r\n";
messages += " --tun-route=[yes|no] \\\r\n";
messages += " --tun-protect=[yes|no] \\\r\n";
#else
messages += " --tun-ssmt=[4] \\\r\n";
#endif
#endif
#if defined(_LINUX) || defined(_MACOS)
messages += " --tun-promisc=[yes|no] \\\r\n";
#endif
messages += " --dns=[8.8.8.8,8.8.4.4] \\\r\n";
#if defined(_WIN32)
messages += " --set-http-proxy=[yes|no] \\\r\n";
#endif
messages += " --block-quic=[yes|no] \\\r\n";
messages += " --bypass-iplist=[./ip.txt] \\\r\n";
messages += " --dns-rules=[./dns-rules.txt] \\\r\n";
messages += " --firewall-rules=[./firewall-rules.txt] \r\n";
messages += "Commands:\r\n";
messages += " ./" + execution_file_name + " --help \r\n";
messages += " ./" + execution_file_name + " --pull-iplist [[ip.txt]/[CN]] \r\n";
#if defined(_WIN32)
messages += " ./" + execution_file_name + " --system-network-reset \r\n";
messages += " ./" + execution_file_name + " --system-network-preferred-ipv4 \r\n";
messages += " ./" + execution_file_name + " --system-network-preferred-ipv6 \r\n";
messages += " ./" + execution_file_name + " --system-network-optimization \r\n";
messages += " ./" + execution_file_name + " --no-lsp \"C:\\Windows\\System32\\wsl.exe\" \r\n";
#endif
messages += "Contact us:\r\n";
messages += " https://t.me/supersocksr_group \r\n";
messages += "Dependencies: ";
messages += "boost@" + GetBoostVersionString();
#if defined(__GLIBC__) && defined(__GLIBC_MINOR__) /* _GNU_SOURCE, _BSD_SOURCE */
messages += ", libc@" + GetVersionString(__GLIBC__, __GLIBC_MINOR__);
#if defined(__MUSL__)
messages += "/musl";
#else
messages += "/gun";
#endif
#endif
#if defined(LIBCURL_VERSION_MAJOR)
messages += ", curl@" + GetVersionString(LIBCURL_VERSION_MAJOR, LIBCURL_VERSION_MINOR, LIBCURL_VERSION_PATCH);
#endif
#if defined(OPENSSL_VERSION_MAJOR)
messages += ", openssl@" + GetVersionString(OPENSSL_VERSION_MAJOR, OPENSSL_VERSION_MINOR, OPENSSL_VERSION_PATCH);
#else
messages += ", openssl@1.1.1";
#endif
#if defined(JEMALLOC_VERSION_MAJOR)
messages += ", jemalloc@" + GetVersionString(JEMALLOC_VERSION_MAJOR, JEMALLOC_VERSION_MINOR, JEMALLOC_VERSION_BUGFIX);
#endif
messages += "\r\n";
fprintf(stdout,
messages.data(),
PPP_APPLICATION_VERSION,
execution_file_name.data(),
#if defined(_MACOS)
"utun0"
#else
BOOST_BEAST_VERSION_STRING
#endif
);
}
boost::asio::ip::address PppApplication::GetNetworkAddress(const char* name, int MIN_PREFIX_ADDRESS, int MAX_PREFIX_ADDRESS, int argc, const char* argv[]) noexcept
{
ppp::string address_string = ppp::GetCommandArgument(name, argc, argv);
if (address_string.empty())
{
return boost::asio::ip::address_v4::any();
}
address_string = ppp::LTrim<ppp::string>(address_string);
address_string = ppp::RTrim<ppp::string>(address_string);