-
Notifications
You must be signed in to change notification settings - Fork 2
/
zerotiermanager.cpp
507 lines (446 loc) · 16.5 KB
/
zerotiermanager.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
#include "zerotiermanager.h"
#include "ui_zerotiermanager.h"
#include "networkinformation.h"
#include <QMessageBox>
#include <QCloseEvent>
#include <QAction>
#include <QMenu>
#include <QList>
#include <QProcess>
#include <QStandardPaths>
#include <QDir>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QHostAddress>
#include <QTableWidget>
#include <QDebug>
#include <QSettings>
#include <QDesktopServices>
ZeroTierManager::ZeroTierManager(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::ZeroTierManager)
{
ui->setupUi(this);
createActions();
createTrayIcon();
QIcon icon = QIcon(":/zerotier-one");
trayIcon->setIcon(icon);
QStringList networks;
QSettings config("jimmy.stelzer","zerotier-one-gui");
networks = config.value("networks").toStringList();
foreach(auto network, networks){
ztonStatus net;
net.id = network;
configuratedNetwork.push_back(net);
addActionMenu(network, false);
}
updateTrayMenu();
updateStatusTimer = new QTimer(this);
connect(updateStatusTimer, &QTimer::timeout, this, QOverload<>::of(&ZeroTierManager::updateStatus));
updateStatusTimer->start(500);
ui->lstCurrentNetwork->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
ui->lstCurrentNetwork->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
ui->lstCurrentNetwork->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
ui->lstCurrentNetwork->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->lstCurrentNetwork->setSelectionMode(QAbstractItemView::SingleSelection);
ui->lstCurrentNetwork->verticalHeader()->hide();
trayIcon->show();
}
ZeroTierManager::~ZeroTierManager()
{
delete ui;
}
void ZeroTierManager::closeEvent(QCloseEvent *event)
{
if (trayIcon->isVisible()) {
hide();
event->ignore();
}
}
void ZeroTierManager::manageNetwork(bool checked)
{
Q_UNUSED(checked);
this->raise();
this->show();
}
void ZeroTierManager::createActions()
{
quitAction = new QAction(tr("&Quit"), this);
connect(quitAction, &QAction::triggered, qApp, &QCoreApplication::quit);
addAction = new QAction(tr("&Manage network"), this);
connect(addAction, &QAction::triggered, this, &ZeroTierManager::manageNetwork);
openCentralAction = new QAction(tr("ZeroTier &Central"), this);
connect(openCentralAction, &QAction::triggered, this, &ZeroTierManager::openCentral);
}
void ZeroTierManager::createTrayIcon()
{
trayIconMenu = new QMenu(this);
trayIconMenu->addAction(addAction);
separatorAction = trayIconMenu->addSeparator();
trayIconMenu->addAction(openCentralAction);
quitSeparatorAction = trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
trayIcon = new QSystemTrayIcon(this);
trayIcon->setContextMenu(trayIconMenu);
connect(trayIcon, &QSystemTrayIcon::activated, this, &ZeroTierManager::trayActivated);
}
bool ZeroTierManager::checkServiceIsRunning()
{
QProcess process;
process.start("systemctl", QStringList() << "show" << "zerotier-one.service" << "--no-pager" << "-p" << "ActiveState" << "--value");
process.waitForFinished();
QString output = process.readAllStandardOutput();
if(output.startsWith("active")){
return true;
}
return false;
}
bool ZeroTierManager::checkHavePkexec()
{
QProcess process;
process.start("whereis", QStringList() << "-b" << "pkexec");
process.waitForFinished();
QString output = process.readAllStandardOutput();
if(output.length() > 8){
return true;
}
return false;
}
bool ZeroTierManager::checkUserToken()
{
QStringList dir = QStandardPaths::standardLocations(QStandardPaths::HomeLocation);
if(dir.length() > 0){
QString tokenFile = dir.first() + QDir::separator() + USER_TOKEN_FILE;
if(QFileInfo::exists(tokenFile)){
return true;
}
}
return false;
}
void ZeroTierManager::copyAuthToken()
{
QStringList dir = QStandardPaths::standardLocations(QStandardPaths::HomeLocation);
if(dir.length() > 0){
QString tokenFilename = dir.first() + QDir::separator() + USER_TOKEN_FILE;
QProcess process;
process.start("sh", QStringList() << "-c" << "pkexec cat /var/lib/zerotier-one/authtoken.secret >> " + tokenFilename);
process.waitForFinished();
if(process.exitCode() == QProcess::NormalExit){
QFile::setPermissions(tokenFilename, QFileDevice::ReadUser|QFileDevice::WriteUser);
haveUserToken = checkUserToken();
}
}
}
void ZeroTierManager::addActionMenu(QString name, bool check)
{
QAction *act = new QAction(name, this);
act->setChecked(check);
act->setCheckable(true);
networkMeuActions.push_back(act);
connect(act, &QAction::triggered, this, &ZeroTierManager::trayMenuTriggered);
}
void ZeroTierManager::updateTrayMenu()
{
foreach(auto netAct, networkMeuActions){
bool hasToInsert = true;
int dynamicActionsSize = trayIconMenu->actions().size() - 4 + 1;
for(int idx=1; idx < dynamicActionsSize; idx++){
if(trayIconMenu->actions().at(idx)->text().startsWith(netAct->text().mid(0,16))){
hasToInsert = false;
break;
}
}
if(hasToInsert){
trayIconMenu->insertAction(separatorAction, netAct);
}
}
}
void ZeroTierManager::updateStatus()
{
if(updateStatusTimer->interval() != 10000){
updateStatusTimer->setInterval(10000);
}
serviceIsRunning = checkServiceIsRunning();
havePkexec = checkHavePkexec();
if(!havePkexec){
QMessageBox::critical(nullptr, QObject::tr("Check pkexec"),
QObject::tr("I couldn't find pkexec "
"on this system. This tool is required."));
qApp->quit();
return;
}
if(!serviceIsRunning){
QMessageBox::critical(nullptr, QObject::tr("ZeroTier One Service"),
QObject::tr("The ZeroTier One is not runnning "
"on this system. We will try to start the service."));
for(int i=0; i < 3; i++){
if(startService() && (serviceIsRunning = checkServiceIsRunning()) == true){
break;
}
}
if(!serviceIsRunning){
QMessageBox::critical(nullptr, QObject::tr("ZeroTier One Service"),
QObject::tr("Fail to start the ZeroTier One service."));
qApp->quit();
return;
}
}
haveUserToken = checkUserToken();
if(!haveUserToken){
copyAuthToken();
}
updateNetworkStatus();
}
bool ZeroTierManager::startService()
{
QProcess process;
process.start("pkexec", QStringList() << "systemctl" << "start" << "zerotier-one.service");
process.waitForFinished();
if(process.exitCode() == QProcess::NormalExit){
return true;
}
return false;
}
void ZeroTierManager::updateNetworkStatus()
{
QJsonDocument jsonDoc = getNetworkInformation();
QStringList networks;
for(int i=0; i < configuratedNetwork.length(); i++){
networks << configuratedNetwork[i].id;
configuratedNetwork[i].hasToUpdate = (configuratedNetwork[i].status == false);
configuratedNetwork[i].status = false;
configuratedNetwork[i].ipv4 = "";
configuratedNetwork[i].ipv6 = "";
}
QSettings config("jimmy.stelzer","zerotier-one-gui");
config.setValue("networks", networks);
if(!jsonDoc.isNull()){
if(jsonDoc.isArray()){
foreach(auto obj, jsonDoc.array()){
if(obj.isObject()){
QJsonObject jsonObj = obj.toObject();
ztonStatus nztonStatus;
nztonStatus.id = jsonObj.value("id").toString();
nztonStatus.macAddr = jsonObj.value("mac").toString();
nztonStatus.status = (jsonObj.value("status").toString() == "OK");
nztonStatus.name = jsonObj.value("name").toString();
foreach(auto objIp, jsonObj.value("assignedAddresses").toArray()){
QHostAddress checkIpVersion(objIp.toString());
if(checkIpVersion.protocol() == QAbstractSocket::NetworkLayerProtocol::IPv4Protocol){
nztonStatus.ipv4 = objIp.toString();
}else if(checkIpVersion.protocol() == QAbstractSocket::NetworkLayerProtocol::IPv6Protocol){
nztonStatus.ipv6 = objIp.toString();
}
}
int idx = configuratedNetwork.indexOf(nztonStatus);
if(idx == -1){
configuratedNetwork.push_back(nztonStatus);
}else{
nztonStatus.hasToUpdate = (configuratedNetwork[idx].hasToUpdate && !nztonStatus.status);
configuratedNetwork[idx] = nztonStatus;
}
}
}
}
}
foreach(auto action, networkMeuActions){
bool hasToRemove = true;
for(int i=0; i < configuratedNetwork.length(); i++){
if(action->text().startsWith(configuratedNetwork[i].id)){
hasToRemove = false;
if(configuratedNetwork[i].name.length() > 0){
action->setText(configuratedNetwork[i].id + " (" + configuratedNetwork[i].name + ")");
}
action->setChecked(configuratedNetwork[i].status);
}
}
if(hasToRemove){
trayIconMenu->removeAction(action);
networkMeuActions.removeAll(action);
action->deleteLater();
}
}
bool restoreSelection = false;
QItemSelectionModel *select = ui->lstCurrentNetwork->selectionModel();
ui->btnToogleConnection->setEnabled(false);
ui->btnInformation->setEnabled(false);
ui->btnRemove->setEnabled(false);
int currentSelectedRow = -1;
if((restoreSelection = select->hasSelection()) == true){
QModelIndexList indexList = select->selectedIndexes();
currentSelectedRow = indexList.at(0).row();
}
ui->lstCurrentNetwork->setRowCount(0);
for(int i=0; i < configuratedNetwork.length(); i++){
ui->lstCurrentNetwork->insertRow(ui->lstCurrentNetwork->rowCount());
ui->lstCurrentNetwork->setItem(i,0, new QTableWidgetItem(configuratedNetwork[i].id));
ui->lstCurrentNetwork->setItem(i,1, new QTableWidgetItem(configuratedNetwork[i].name));
ui->lstCurrentNetwork->setItem(i,2, new QTableWidgetItem((configuratedNetwork[i].status) ? QString(tr("OK")) : QString("-")));
}
if(restoreSelection && currentSelectedRow > -1){
ui->lstCurrentNetwork->selectRow(currentSelectedRow);
ui->btnToogleConnection->setEnabled(true);
ui->btnInformation->setEnabled(true);
ui->btnRemove->setEnabled(true);
}
}
int ZeroTierManager::selectedNetwork()
{
QItemSelectionModel *select = ui->lstCurrentNetwork->selectionModel();
int currentSelectedRow = -1;
if(select->hasSelection() == true){
QModelIndexList indexList = select->selectedIndexes();
currentSelectedRow = indexList.at(0).row();
}
return currentSelectedRow;
}
QJsonDocument ZeroTierManager::getNetworkInformation()
{
QProcess process;
process.start("zerotier-cli", QStringList() << "-j" << "listnetworks");
process.waitForFinished();
QString output = process.readAllStandardOutput();
QJsonDocument jsonDoc = QJsonDocument::fromJson(output.toUtf8());
return jsonDoc;
}
bool ZeroTierManager::isNetworkJoinedInZerotier(QString networkId)
{
QJsonDocument currentNetworks = getNetworkInformation();
if(!currentNetworks.isNull()){
if(currentNetworks.isArray()){
foreach(auto obj, currentNetworks.array()){
if(obj.isObject()){
QJsonObject jsonObj = obj.toObject();
ztonStatus nztonStatus;
if(jsonObj.value("id").toString() == networkId){
return true;
}
}
}
}
}
return false;
}
void ZeroTierManager::zerotierJoinNetwork(QString networkId)
{
QProcess process;
process.start("zerotier-cli", QStringList() << "join" << networkId);
process.waitForFinished();
QString output = process.readAllStandardOutput();
}
void ZeroTierManager::zerotierLeaveNetwork(QString networkId)
{
QProcess process;
process.start("zerotier-cli", QStringList() << "leave" << networkId);
process.waitForFinished();
QString output = process.readAllStandardOutput();
}
void ZeroTierManager::on_btnOk_clicked()
{
hide();
}
void ZeroTierManager::on_lstCurrentNetwork_currentCellChanged(int currentRow, int currentColumn, int previousRow, int previousColumn)
{
Q_UNUSED(currentRow) Q_UNUSED(currentColumn) Q_UNUSED(previousRow) Q_UNUSED(previousColumn)
ui->btnToogleConnection->setEnabled(true);
ui->btnInformation->setEnabled(true);
ui->btnRemove->setEnabled(true);
}
void ZeroTierManager::on_btnToogleConnection_clicked()
{
int currentSelectedRow = selectedNetwork();
if(currentSelectedRow >= 0){
QTableWidgetItem *item = ui->lstCurrentNetwork->item(currentSelectedRow, 0);
if(isNetworkJoinedInZerotier(item->text())){
zerotierLeaveNetwork(item->text());
}else{
zerotierJoinNetwork(item->text());
}
}
updateNetworkStatus();
}
void ZeroTierManager::on_btnRemove_clicked()
{
int currentSelectedRow = selectedNetwork();
if(currentSelectedRow >= 0){
QTableWidgetItem *item = ui->lstCurrentNetwork->item(currentSelectedRow, 0);
if(isNetworkJoinedInZerotier(item->text())){
zerotierLeaveNetwork(item->text());
ztonStatus nztonStatus;
nztonStatus.id = item->text();
int idx = configuratedNetwork.indexOf(nztonStatus);
if(idx > -1){
configuratedNetwork.removeAt(idx);
}
}
ui->lstCurrentNetwork->clearSelection();
}
updateNetworkStatus();
}
void ZeroTierManager::on_btnInformation_clicked()
{
int currentSelectedRow = selectedNetwork();
bool hasInfo = false;
if(currentSelectedRow >= 0){
QTableWidgetItem *item = ui->lstCurrentNetwork->item(currentSelectedRow, 0);
QJsonDocument jsonDoc = getNetworkInformation();
if(!jsonDoc.isNull()){
if(jsonDoc.isArray()){
foreach(auto obj, jsonDoc.array()){
if(obj.isObject()){
QJsonObject jsonObj = obj.toObject();
if(jsonObj.value("id").toString() == item->text()){
hasInfo = true;
NetworkInformation *info = new NetworkInformation(jsonObj, nullptr);
info->exec();
info->deleteLater();
break;
}
}
}
}
}
}
if(!hasInfo){
QMessageBox::information(this,tr("Network Information"), tr("There is no information about this network at this moment. You must connect to this network to see this information."));
}
}
void ZeroTierManager::on_btnJoin_clicked()
{
QString networkId = ui->edtNetworkId->text();
if(!isNetworkJoinedInZerotier(networkId)){
ztonStatus nztonStatus;
nztonStatus.id = networkId;
int idx = configuratedNetwork.indexOf(nztonStatus);
if(idx == -1){
configuratedNetwork.push_back(nztonStatus);
}
addActionMenu(nztonStatus.id, false);
updateTrayMenu();
zerotierJoinNetwork(networkId);
}
updateNetworkStatus();
}
void ZeroTierManager::trayActivated(QSystemTrayIcon::ActivationReason reason)
{
if(reason == QSystemTrayIcon::DoubleClick){
manageNetwork(false);
}
}
void ZeroTierManager::trayMenuTriggered(bool status)
{
QAction* caller = qobject_cast<QAction*>(sender());
Q_ASSERT(caller != nullptr);
QString id = caller->text().mid(0,16);
if(isNetworkJoinedInZerotier(id) && status == false){
zerotierLeaveNetwork(id);
}else if (!isNetworkJoinedInZerotier(id) && status == true){
zerotierJoinNetwork(id);
}
}
void ZeroTierManager::openCentral(bool checked)
{
Q_UNUSED(checked);
QDesktopServices::openUrl(QUrl("https://my.zerotier.com", QUrl::TolerantMode));
}