mainwindow.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2014 ZeroTier Networks LLC
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include <string>
  28. #include <map>
  29. #include <set>
  30. #include <vector>
  31. #include <stdexcept>
  32. #include <utility>
  33. #include <QClipboard>
  34. #include <QMutex>
  35. #include <QCoreApplication>
  36. #include <QDir>
  37. #include <QFile>
  38. #include <QMessageBox>
  39. #include <QDebug>
  40. #include <QProcess>
  41. #include <QStringList>
  42. #include <QVBoxLayout>
  43. #include <QScrollBar>
  44. #include <QEventLoop>
  45. #include <QFont>
  46. #include "main.h"
  47. #include "mainwindow.h"
  48. #include "aboutwindow.h"
  49. #include "networkwidget.h"
  50. #include "ui_mainwindow.h"
  51. #include "ui_quickstartdialog.h"
  52. #ifdef __APPLE__
  53. #include <stdio.h>
  54. #include <string.h>
  55. #include <unistd.h>
  56. #include <sys/types.h>
  57. #include <sys/stat.h>
  58. #include "mac_doprivileged.h"
  59. #endif
  60. #include "../node/Utils.hpp"
  61. #include "../node/Identity.hpp"
  62. #include "../node/Defaults.hpp"
  63. // Globally visible
  64. ZeroTier::NodeControlClient *zeroTierClient = (ZeroTier::NodeControlClient *)0;
  65. // Main window instance for app
  66. QMainWindow *mainWindow = (MainWindow *)0;
  67. // Handles message from ZeroTier One service
  68. static void handleZTMessage(void *arg,const char *line)
  69. {
  70. static std::vector<std::string> ztReplies;
  71. static QMutex ztReplies_m;
  72. ztReplies_m.lock();
  73. if (line) {
  74. //printf("%s\n",line);
  75. if ((line[0] == '.')&&(line[1] == (char)0)) {
  76. // The message is packed into an event and sent to the main window where
  77. // the actual parsing code lives.
  78. MainWindow::ZTMessageEvent *event = new MainWindow::ZTMessageEvent(ztReplies);
  79. ztReplies.clear();
  80. QCoreApplication::postEvent(mainWindow,event); // must post since this may be another thread
  81. } else if (line[0]) {
  82. ztReplies.push_back(std::string(line));
  83. }
  84. }
  85. ztReplies_m.unlock();
  86. }
  87. MainWindow::MainWindow(QWidget *parent) :
  88. QMainWindow(parent),
  89. ui(new Ui::MainWindow),
  90. pollServiceTimerId(-1)
  91. {
  92. mainWindow = this;
  93. ui->setupUi(this);
  94. if (ui->networkListWidget->verticalScrollBar())
  95. ui->networkListWidget->verticalScrollBar()->setSingleStep(8);
  96. #ifdef __APPLE__
  97. QWidgetList widgets = this->findChildren<QWidget*>();
  98. foreach(QWidget *widget, widgets)
  99. widget->setAttribute(Qt::WA_MacShowFocusRect,false);
  100. #endif
  101. #ifdef __WINDOWS__
  102. // Windows operates at a different DPI, so we have to rescale the default Qt
  103. // font sizes so everything isn't huge. Yeah.
  104. QWidgetList widgets = this->findChildren<QWidget*>();
  105. foreach(QWidget *widget, widgets) {
  106. if (typeid(*widget) != typeid(*ui->menuFile)) { // menus don't need the DPI shift apparently
  107. QFont font(widget->font());
  108. font.setPointSizeF(font.pointSizeF() * 0.75);
  109. widget->setFont(font);
  110. }
  111. }
  112. this->raise();
  113. #endif
  114. ui->noNetworksLabel->setVisible(true);
  115. ui->noNetworksLabel->setText("Connecting to Service...");
  116. ui->bottomContainerWidget->setVisible(false);
  117. ui->networkListWidget->setVisible(false);
  118. this->firstTimerTick = true;
  119. this->pollServiceTimerId = this->startTimer(200);
  120. this->cyclesSinceResponseFromService = 0;
  121. }
  122. MainWindow::~MainWindow()
  123. {
  124. delete ui;
  125. delete zeroTierClient;
  126. zeroTierClient = (ZeroTier::NodeControlClient *)0;
  127. mainWindow = (MainWindow *)0;
  128. }
  129. void MainWindow::timerEvent(QTimerEvent *event) // event can be null since code also calls this directly
  130. {
  131. if (this->isHidden())
  132. return;
  133. if (this->pollServiceTimerId < 0)
  134. return;
  135. // Show quick start dialog on first launch, then reset timer to normal rate
  136. if (this->firstTimerTick) {
  137. this->firstTimerTick = false;
  138. this->killTimer(this->pollServiceTimerId);
  139. if (!settings->value("shown_quickStart",false).toBool()) {
  140. on_actionQuick_Start_triggered();
  141. settings->setValue("shown_quickStart",true);
  142. settings->sync();
  143. }
  144. this->pollServiceTimerId = this->startTimer(2000);
  145. }
  146. if (!zeroTierClient) {
  147. #ifdef __APPLE__
  148. if ((!QFile::exists(ZeroTier::NodeControlClient::authTokenDefaultUserPath()))&&(QFile::exists("/Library/Application Support/ZeroTier/One/zerotier-one"))) {
  149. // Authorize user by copying auth token into local home directory
  150. QMessageBox::information(this,"Authorization Needed","Administrator privileges are required to allow the current user to control ZeroTier One on this computer. (You only have to do this once.)",QMessageBox::Ok,QMessageBox::NoButton);
  151. std::string homePath(QDir::homePath().toStdString());
  152. QString zt1Caches(QDir::homePath() + "/Library/Caches/ZeroTier/One");
  153. QDir::root().mkpath(zt1Caches);
  154. std::string tmpPath((zt1Caches + "/auth.sh").toStdString());
  155. FILE *scr = fopen(tmpPath.c_str(),"w");
  156. if (!scr) {
  157. QMessageBox::critical(this,"Cannot Authorize","Unable to authorize this user to administrate ZeroTier One. (Cannot write to temporary Library/Caches/ZeroTier/One folder.)",QMessageBox::Ok,QMessageBox::NoButton);
  158. QApplication::exit(1);
  159. return;
  160. }
  161. fprintf(scr,"#!/bin/bash\n");
  162. fprintf(scr,"export PATH=\"/bin:/usr/bin:/sbin:/usr/sbin\"\n");
  163. fprintf(scr,"if [ -f '/Library/Application Support/ZeroTier/One/authtoken.secret' ]; then\n");
  164. fprintf(scr," mkdir -p '%s/Library/Application Support/ZeroTier/One'\n",homePath.c_str());
  165. fprintf(scr," chown %d '%s/Library/Application Support/ZeroTier'\n",(int)getuid(),homePath.c_str());
  166. fprintf(scr," chgrp %d '%s/Library/Application Support/ZeroTier'\n",(int)getgid(),homePath.c_str());
  167. fprintf(scr," chmod 0700 '%s/Library/Application Support/ZeroTier'\n",homePath.c_str());
  168. fprintf(scr," chown %d '%s/Library/Application Support/ZeroTier/One'\n",(int)getuid(),homePath.c_str());
  169. fprintf(scr," chgrp %d '%s/Library/Application Support/ZeroTier/One'\n",(int)getgid(),homePath.c_str());
  170. fprintf(scr," chmod 0700 '%s/Library/Application Support/ZeroTier/One'\n",homePath.c_str());
  171. fprintf(scr," cp -f '/Library/Application Support/ZeroTier/One/authtoken.secret' '%s/Library/Application Support/ZeroTier/One/authtoken.secret'\n",homePath.c_str());
  172. fprintf(scr," chown %d '%s/Library/Application Support/ZeroTier/One/authtoken.secret'\n",(int)getuid(),homePath.c_str());
  173. fprintf(scr," chgrp %d '%s/Library/Application Support/ZeroTier/One/authtoken.secret'\n",(int)getgid(),homePath.c_str());
  174. fprintf(scr," chmod 0600 '%s/Library/Application Support/ZeroTier/One/authtoken.secret'\n",homePath.c_str());
  175. fprintf(scr,"fi\n");
  176. fprintf(scr,"exit 0\n");
  177. fclose(scr);
  178. chmod(tmpPath.c_str(),0755);
  179. macExecutePrivilegedShellCommand((std::string("'")+tmpPath+"' >>/dev/null 2>&1").c_str());
  180. unlink(tmpPath.c_str());
  181. }
  182. #endif // __APPLE__
  183. try {
  184. std::string buf;
  185. if (ZeroTier::Utils::readFile((ZeroTier::ZT_DEFAULTS.defaultHomePath + ZT_PATH_SEPARATOR_S + "identity.public").c_str(),buf)) {
  186. ZeroTier::Identity id;
  187. if (id.fromString(buf)) {
  188. std::string authToken(ZeroTier::NodeControlClient::getAuthToken(ZeroTier::NodeControlClient::authTokenDefaultUserPath(),false));
  189. if (!authToken.length())
  190. authToken = ZeroTier::NodeControlClient::getAuthToken((ZeroTier::ZT_DEFAULTS.defaultHomePath + ZT_PATH_SEPARATOR_S + "authtoken.secret").c_str(),false);
  191. zeroTierClient = new ZeroTier::NodeControlClient((std::string(ZT_IPC_ENDPOINT_BASE) + id.address().toString()).c_str(),authToken.c_str(),&handleZTMessage,this);
  192. const char *err = zeroTierClient->error();
  193. if (err) {
  194. delete zeroTierClient;
  195. zeroTierClient = (ZeroTier::NodeControlClient *)0;
  196. }
  197. }
  198. }
  199. } catch ( ... ) {
  200. zeroTierClient = (ZeroTier::NodeControlClient *)0;
  201. }
  202. }
  203. if (++this->cyclesSinceResponseFromService >= 3) {
  204. if (this->cyclesSinceResponseFromService == 3) {
  205. QMessageBox::warning(this,"Service Not Running","Can't connect to the ZeroTier One service. Is it running?",QMessageBox::Ok);
  206. }
  207. ui->noNetworksLabel->setVisible(true);
  208. ui->noNetworksLabel->setText("Connecting to Service...");
  209. ui->bottomContainerWidget->setVisible(false);
  210. ui->networkListWidget->setVisible(false);
  211. }
  212. if (zeroTierClient) {
  213. zeroTierClient->send("info");
  214. zeroTierClient->send("listnetworks");
  215. zeroTierClient->send("listpeers");
  216. }
  217. }
  218. void MainWindow::customEvent(QEvent *event)
  219. {
  220. ZTMessageEvent *m = (ZTMessageEvent *)event; // only one custom event type so far
  221. if (m->ztMessage.size() == 0)
  222. return;
  223. std::vector<std::string> hdr(ZeroTier::NodeControlClient::splitLine(m->ztMessage[0]));
  224. if (hdr.size() < 2)
  225. return;
  226. if (hdr[0] != "200")
  227. return;
  228. this->cyclesSinceResponseFromService = 0;
  229. if (hdr[1] == "info") {
  230. if (hdr.size() >= 3)
  231. this->myAddress = hdr[2].c_str();
  232. if (hdr.size() >= 4)
  233. this->myStatus = hdr[3].c_str();
  234. if (hdr.size() >= 5)
  235. this->myVersion = hdr[4].c_str();
  236. } else if (hdr[1] == "listnetworks") {
  237. std::map< std::string,std::vector<std::string> > newNetworks;
  238. for(unsigned long i=1;i<m->ztMessage.size();++i) {
  239. std::vector<std::string> l(ZeroTier::NodeControlClient::splitLine(m->ztMessage[i]));
  240. // 200 listnetworks <nwid> <name> <mac> <status> <config age> <type> <dev> <ips>
  241. if ((l.size() == 10)&&(l[2].length() == 16))
  242. newNetworks[l[2]] = l;
  243. }
  244. if (newNetworks != networks) {
  245. networks = newNetworks;
  246. for (bool removed=true;removed;) {
  247. removed = false;
  248. for(int r=0;r<ui->networkListWidget->count();++r) {
  249. NetworkWidget *nw = (NetworkWidget *)ui->networkListWidget->itemWidget(ui->networkListWidget->item(r));
  250. if (!networks.count(nw->networkId())) {
  251. ui->networkListWidget->setVisible(false); // HACK to prevent an occasional crash here, discovered through hours of shotgun debugging... :P
  252. delete ui->networkListWidget->takeItem(r);
  253. removed = true;
  254. break;
  255. }
  256. }
  257. }
  258. ui->networkListWidget->setVisible(true);
  259. std::set<std::string> alreadyDisplayed;
  260. for(int r=0;r<ui->networkListWidget->count();++r) {
  261. NetworkWidget *nw = (NetworkWidget *)ui->networkListWidget->itemWidget(ui->networkListWidget->item(r));
  262. if (networks.count(nw->networkId()) > 0) {
  263. alreadyDisplayed.insert(nw->networkId());
  264. std::vector<std::string> &l = networks[nw->networkId()];
  265. nw->setNetworkName(l[3]);
  266. nw->setMAC(l[4]);
  267. nw->setStatus(l[5],l[6]);
  268. nw->setNetworkType(l[7]);
  269. nw->setNetworkDeviceName(l[8]);
  270. nw->setIps(l[9]);
  271. }
  272. }
  273. for(std::map< std::string,std::vector<std::string> >::iterator nwdata(networks.begin());nwdata!=networks.end();++nwdata) {
  274. if (alreadyDisplayed.count(nwdata->first) == 0) {
  275. std::vector<std::string> &l = nwdata->second;
  276. NetworkWidget *nw = new NetworkWidget((QWidget *)0,nwdata->first);
  277. nw->setNetworkName(l[3]);
  278. nw->setMAC(l[4]);
  279. nw->setStatus(l[5],l[6]);
  280. nw->setNetworkType(l[7]);
  281. nw->setNetworkDeviceName(l[8]);
  282. nw->setIps(l[9]);
  283. QListWidgetItem *item = new QListWidgetItem();
  284. item->setSizeHint(nw->sizeHint());
  285. ui->networkListWidget->addItem(item);
  286. ui->networkListWidget->setItemWidget(item,nw);
  287. }
  288. }
  289. }
  290. } else if (hdr[1] == "listpeers") {
  291. this->numPeers = 0;
  292. for(unsigned long i=1;i<m->ztMessage.size();++i)
  293. ++this->numPeers;
  294. } else
  295. return;
  296. if (!ui->networkListWidget->count()) {
  297. ui->noNetworksLabel->setText("You Have Not Joined Any Networks");
  298. ui->noNetworksLabel->setVisible(true);
  299. } else ui->noNetworksLabel->setVisible(false);
  300. if (!ui->bottomContainerWidget->isVisible())
  301. ui->bottomContainerWidget->setVisible(true);
  302. if (!ui->networkListWidget->isVisible())
  303. ui->networkListWidget->setVisible(true);
  304. if (this->myAddress.size())
  305. ui->addressButton->setText(this->myAddress);
  306. else ui->addressButton->setText(" ");
  307. QString st(this->myStatus);
  308. st += ", v";
  309. st += this->myVersion;
  310. st += ", ";
  311. st += QString::number(this->numPeers);
  312. st += " peers";
  313. ui->statusLabel->setText(st);
  314. }
  315. void MainWindow::on_joinNetworkButton_clicked()
  316. {
  317. QString toJoin(ui->networkIdLineEdit->text());
  318. ui->networkIdLineEdit->setText(QString());
  319. if (!zeroTierClient) // sanity check
  320. return;
  321. if (toJoin.size() != 16) {
  322. QMessageBox::information(this,"Invalid Network ID","The network ID you entered was not valid. Enter a 16-digit hexadecimal network ID, like '8056c2e21c000001'.",QMessageBox::Ok,QMessageBox::NoButton);
  323. return;
  324. }
  325. zeroTierClient->send((QString("join ") + toJoin).toStdString());
  326. }
  327. void MainWindow::on_actionAbout_triggered()
  328. {
  329. AboutWindow *about = new AboutWindow(this);
  330. about->show();
  331. }
  332. void MainWindow::on_networkIdLineEdit_textChanged(const QString &text)
  333. {
  334. QString newText;
  335. for(QString::const_iterator i(text.begin());i!=text.end();++i) {
  336. switch(i->toLatin1()) {
  337. case '0': newText.append('0'); break;
  338. case '1': newText.append('1'); break;
  339. case '2': newText.append('2'); break;
  340. case '3': newText.append('3'); break;
  341. case '4': newText.append('4'); break;
  342. case '5': newText.append('5'); break;
  343. case '6': newText.append('6'); break;
  344. case '7': newText.append('7'); break;
  345. case '8': newText.append('8'); break;
  346. case '9': newText.append('9'); break;
  347. case 'a': newText.append('a'); break;
  348. case 'b': newText.append('b'); break;
  349. case 'c': newText.append('c'); break;
  350. case 'd': newText.append('d'); break;
  351. case 'e': newText.append('e'); break;
  352. case 'f': newText.append('f'); break;
  353. case 'A': newText.append('a'); break;
  354. case 'B': newText.append('b'); break;
  355. case 'C': newText.append('c'); break;
  356. case 'D': newText.append('d'); break;
  357. case 'E': newText.append('e'); break;
  358. case 'F': newText.append('f'); break;
  359. default: break;
  360. }
  361. }
  362. if (newText.size() > 16)
  363. newText.truncate(16);
  364. ui->networkIdLineEdit->setText(newText);
  365. }
  366. void MainWindow::on_addressButton_clicked()
  367. {
  368. QApplication::clipboard()->setText(this->myAddress);
  369. }
  370. void MainWindow::on_actionQuick_Start_triggered()
  371. {
  372. Ui::QuickstartDialog qd;
  373. QDialog *qdd = new QDialog(this);
  374. qd.setupUi(qdd);
  375. qdd->setModal(false);
  376. qdd->show();
  377. }