-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauto-toggle-vpn.cpp
222 lines (194 loc) · 6.97 KB
/
auto-toggle-vpn.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
#include <array>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <memory>
#include <nlohmann/json.hpp>
#include <string>
#include <vector>
using namespace std;
using namespace std::filesystem;
using json = nlohmann::json;
// Function declarations
void generateExampleConfigFile(const path& configFilePath);
void printHelp();
void printVersion();
void printUnknown(const string& arg);
vector<string> executeCommand(const string& command);
vector<string> getAllEthernetInterfaces();
vector<string> getAllWiFiInterfaces();
bool isInterfaceActive(const string& interfaceName);
bool isAllInterfaceActive(const vector<string>& interfaceNames);
string getCurrentWiFiSSID();
bool isVPNActive(const string& name);
void toggleVPN(const string& serviceName, bool connect);
bool isSSIDHit(const string& currentSSID, const vector<string>& SSIDList);
// Constants
const string ProgramName = "auto-toggle-vpn";
const string ProgramVersion = "0.0.3";
const string configFileName = "config.json";
const path configFilePath = string(getenv("HOME")) + "/.local/" + ProgramName + "/" + configFileName;
// Struct to hold configuration values
struct Config {
string vpnname;
vector<string> ssidlist;
};
// Main function
int main(int argc, char* argv[]) {
if (argc > 1) {
string arg(argv[1]);
if (arg == "-g" or arg == "--generate") {
generateExampleConfigFile(configFilePath.string() + ".example");
} else if (arg == "-v" or arg == "--version") {
printVersion();
} else if (arg == "-h" or arg == "--help") {
printHelp();
} else {
printUnknown(arg);
return 1;
}
return 0;
}
ifstream configFile(configFilePath);
if (!configFile.is_open()) {
cerr << "Error: Failed to open config file." << endl;
return 1;
}
Config config;
try {
json configJson;
configFile >> configJson;
config.vpnname = configJson["vpnname"].get<string>();
config.ssidlist = configJson["ssidlist"].get<vector<string>>();
} catch (const exception& e) {
cerr << "Error: Failed to parse config file. " << e.what() << endl;
return 1;
}
bool isEthernetActive = isAllInterfaceActive(getAllEthernetInterfaces());
bool isWiFiActive = isAllInterfaceActive(getAllWiFiInterfaces());
bool isVPNConnected = isVPNActive(config.vpnname);
if (!isEthernetActive and !isWiFiActive) {
if (isVPNConnected) {
cout << "Stopping VPN" << endl;
toggleVPN(config.vpnname, false);
}
} else {
string currentSSID = getCurrentWiFiSSID();
if (isEthernetActive or isSSIDHit(currentSSID, config.ssidlist)) {
if (isVPNConnected) {
cout << "Stopping VPN" << endl;
toggleVPN(config.vpnname, false);
}
} else {
if (!isVPNConnected) {
cout << "Starting VPN" << endl;
toggleVPN(config.vpnname, true);
}
}
}
return 0;
}
// Utility functions
void generateExampleConfigFile(const path& configFilePath) {
Config exampleConfig;
exampleConfig.vpnname = "Enter your vpn_name, You can find it in Settings - VPN.";
exampleConfig.ssidlist = {"SSID_1", "SSID_2"};
try {
create_directories(configFilePath.parent_path());
ofstream configFile(configFilePath);
if (!configFile.is_open()) {
cerr << "Error: Failed to create example configuration file." << endl;
return;
}
json configJson;
configJson["vpnname"] = exampleConfig.vpnname;
configJson["ssidlist"] = exampleConfig.ssidlist;
configFile << configJson.dump(4) << endl;
configFile.close();
cout << "Successfully generated an example configuration file.\n"
<< "Please make changes to the file located at " << configFilePath
<< " and rename it to 'config.json'." << endl;
} catch (const exception& e) {
cerr << "Error: Failed to generate example configuration file. " << e.what() << endl;
}
}
void printHelp() {
cout << "Usage: " << ProgramName << " [options]\n"
<< "Options:\n"
<< " -g, --generate : Generate config file example\n"
<< " -v, --version : Display program version\n"
<< " -h, --help : Display this help message\n";
}
void printVersion() {
cout << "Program version: " << ProgramVersion << endl;
}
void printUnknown(const string& arg) {
cout << ProgramName + ": option " << arg << " is unknown.\n"
<< ProgramName + ": try '" + ProgramName + " --help' for more information.\n";
}
vector<string> executeCommand(const string& command) {
vector<string> result = {};
array<char, 128> buffer;
shared_ptr<FILE> pipe(popen(command.c_str(), "r"), pclose);
if (!pipe) {
cerr << "Error: Failed to execute command." << endl;
return result;
}
while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
result.push_back(buffer.data());
}
for (auto& str : result) {
if (!str.empty() && str.back() == '\n') {
str.pop_back(); // Remove newline character
}
}
if (result.empty()) {
result.push_back("");
}
return result;
}
vector<string> getAllEthernetInterfaces() {
string command = "networksetup -listnetworkserviceorder | sed -nE '/Ethernet|Dock|LAN/ s|.*Device: (en[0-9]+).*|\\1|p'";
return executeCommand(command);
}
vector<string> getAllWiFiInterfaces() {
string command = "networksetup -listnetworkserviceorder | sed -nE '/Wi-Fi|AirPort/ s|.*Device: (en[0-9]+).*|\\1|p'";
return executeCommand(command);
}
bool isInterfaceActive(const string& interfaceName) {
string command = "ifconfig " + interfaceName + " 2>/dev/null | awk '/status/ {print $2}'";
return executeCommand(command).front() == "active";
}
bool isAllInterfaceActive(const vector<string>& interfaceNames) {
for (const auto& interface : interfaceNames) {
if (isInterfaceActive(interface)) {
return true;
}
}
return false;
}
string getCurrentWiFiSSID() {
string command = "/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -I | awk -F': ' '/^ *SSID:/ {print $2}'";
return executeCommand(command).front();
}
bool isVPNActive(const string& name) {
string command = "networksetup -showpppoestatus " + name;
return executeCommand(command).front() == "connected";
}
void toggleVPN(const string& serviceName, bool connect) {
string command;
if (connect) {
command = "networksetup -connectpppoeservice \"" + serviceName + "\"";
} else {
command = "networksetup -disconnectpppoeservice \"" + serviceName + "\"";
}
executeCommand(command);
}
bool isSSIDHit(const string& currentSSID, const vector<string>& SSIDList) {
for (string ssid : SSIDList) {
if (currentSSID == ssid) {
return true;
}
}
return false;
}