mainwindow.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. // Globally visible
  61. ZeroTier::Node::LocalClient *zeroTierClient = (ZeroTier::Node::LocalClient *)0;
  62. // Main window instance for app
  63. QMainWindow *mainWindow = (MainWindow *)0;
  64. // Handles message from ZeroTier One service
  65. static void handleZTMessage(void *arg,unsigned long id,const char *line)
  66. {
  67. static std::map< unsigned long,std::vector<std::string> > ztReplies;
  68. static QMutex ztReplies_m;
  69. ztReplies_m.lock();
  70. if (*line) {
  71. ztReplies[id].push_back(std::string(line));
  72. ztReplies_m.unlock();
  73. } else { // empty lines conclude transmissions
  74. std::map< unsigned long,std::vector<std::string> >::iterator r(ztReplies.find(id));
  75. if (r != ztReplies.end()) {
  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(r->second);
  79. ztReplies.erase(r);
  80. ztReplies_m.unlock();
  81. QCoreApplication::postEvent(mainWindow,event); // must post since this may be another thread
  82. } else ztReplies_m.unlock();
  83. }
  84. }
  85. MainWindow::MainWindow(QWidget *parent) :
  86. QMainWindow(parent),
  87. ui(new Ui::MainWindow),
  88. pollServiceTimerId(-1)
  89. {
  90. mainWindow = this;
  91. ui->setupUi(this);
  92. if (ui->networkListWidget->verticalScrollBar())
  93. ui->networkListWidget->verticalScrollBar()->setSingleStep(8);
  94. #ifdef __APPLE__
  95. QWidgetList widgets = this->findChildren<QWidget*>();
  96. foreach(QWidget *widget, widgets)
  97. widget->setAttribute(Qt::WA_MacShowFocusRect,false);
  98. #endif
  99. #ifdef __WINDOWS__
  100. QWidgetList widgets = this->findChildren<QWidget*>();
  101. foreach(QWidget *widget, widgets) {
  102. if ((typeid(*widget) != typeid(ui->menuBar))&&(typeid(*widget) != typeid(ui->menuFile))) {
  103. QFont font(widget->font());
  104. font.setPointSizeF(font.pointSizeF() * 0.75);
  105. widget->setFont(font);
  106. }
  107. }
  108. #endif
  109. ui->noNetworksLabel->setVisible(true);
  110. ui->noNetworksLabel->setText("Connecting to Service...");
  111. ui->bottomContainerWidget->setVisible(false);
  112. ui->networkListWidget->setVisible(false);
  113. this->firstTimerTick = true;
  114. this->pollServiceTimerId = this->startTimer(200);
  115. this->cyclesSinceResponseFromService = 0;
  116. }
  117. MainWindow::~MainWindow()
  118. {
  119. delete ui;
  120. delete zeroTierClient;
  121. zeroTierClient = (ZeroTier::Node::LocalClient *)0;
  122. mainWindow = (MainWindow *)0;
  123. }
  124. void MainWindow::timerEvent(QTimerEvent *event) // event can be null since code also calls this directly
  125. {
  126. if (this->isHidden())
  127. return;
  128. if (this->pollServiceTimerId < 0)
  129. return;
  130. if (this->firstTimerTick) {
  131. this->firstTimerTick = false;
  132. this->killTimer(this->pollServiceTimerId);
  133. if (!settings->value("shown_quickStart",false).toBool()) {
  134. on_actionQuick_Start_triggered();
  135. settings->setValue("shown_quickStart",true);
  136. settings->sync();
  137. }
  138. this->pollServiceTimerId = this->startTimer(1500);
  139. }
  140. if (!zeroTierClient) {
  141. std::string authToken;
  142. if (!ZeroTier::Utils::readFile(ZeroTier::Node::LocalClient::authTokenDefaultUserPath().c_str(),authToken)) {
  143. #ifdef __APPLE__
  144. if (QFile::exists("/Library/Application Support/ZeroTier/One/zerotier-one")) {
  145. // Authorize user by copying auth token into local home directory
  146. 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);
  147. std::string homePath(QDir::homePath().toStdString());
  148. QString zt1Caches(QDir::homePath() + "/Library/Caches/ZeroTier/One");
  149. QDir::root().mkpath(zt1Caches);
  150. std::string tmpPath((zt1Caches + "/auth.sh").toStdString());
  151. FILE *scr = fopen(tmpPath.c_str(),"w");
  152. if (!scr) {
  153. 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);
  154. QApplication::exit(1);
  155. return;
  156. }
  157. fprintf(scr,"#!/bin/bash\n");
  158. fprintf(scr,"export PATH=\"/bin:/usr/bin:/sbin:/usr/sbin\"\n");
  159. fprintf(scr,"if [ -f '/Library/Application Support/ZeroTier/One/authtoken.secret' ]; then\n");
  160. fprintf(scr," mkdir -p '%s/Library/Application Support/ZeroTier/One'\n",homePath.c_str());
  161. fprintf(scr," chown %d '%s/Library/Application Support/ZeroTier'\n",(int)getuid(),homePath.c_str());
  162. fprintf(scr," chgrp %d '%s/Library/Application Support/ZeroTier'\n",(int)getgid(),homePath.c_str());
  163. fprintf(scr," chmod 0700 '%s/Library/Application Support/ZeroTier'\n",homePath.c_str());
  164. fprintf(scr," chown %d '%s/Library/Application Support/ZeroTier/One'\n",(int)getuid(),homePath.c_str());
  165. fprintf(scr," chgrp %d '%s/Library/Application Support/ZeroTier/One'\n",(int)getgid(),homePath.c_str());
  166. fprintf(scr," chmod 0700 '%s/Library/Application Support/ZeroTier/One'\n",homePath.c_str());
  167. fprintf(scr," cp -f '/Library/Application Support/ZeroTier/One/authtoken.secret' '%s/Library/Application Support/ZeroTier/One/authtoken.secret'\n",homePath.c_str());
  168. fprintf(scr," chown %d '%s/Library/Application Support/ZeroTier/One/authtoken.secret'\n",(int)getuid(),homePath.c_str());
  169. fprintf(scr," chgrp %d '%s/Library/Application Support/ZeroTier/One/authtoken.secret'\n",(int)getgid(),homePath.c_str());
  170. fprintf(scr," chmod 0600 '%s/Library/Application Support/ZeroTier/One/authtoken.secret'\n",homePath.c_str());
  171. fprintf(scr,"fi\n");
  172. fprintf(scr,"exit 0\n");
  173. fclose(scr);
  174. chmod(tmpPath.c_str(),0755);
  175. macExecutePrivilegedShellCommand((std::string("'")+tmpPath+"' >>/dev/null 2>&1").c_str());
  176. unlink(tmpPath.c_str());
  177. }
  178. #endif
  179. if (!ZeroTier::Utils::readFile(ZeroTier::Node::LocalClient::authTokenDefaultUserPath().c_str(),authToken)) {
  180. if (!ZeroTier::Utils::readFile(ZeroTier::Node::LocalClient::authTokenDefaultSystemPath().c_str(),authToken)) {
  181. QMessageBox::critical(this,"Cannot Authorize","Unable to authorize this user to administrate ZeroTier One. (Did you enter your password correctly?)",QMessageBox::Ok,QMessageBox::NoButton);
  182. QApplication::exit(1);
  183. return;
  184. }
  185. }
  186. }
  187. zeroTierClient = new ZeroTier::Node::LocalClient(authToken.c_str(),0,&handleZTMessage,this);
  188. }
  189. if (++this->cyclesSinceResponseFromService >= 3) {
  190. if (this->cyclesSinceResponseFromService == 3)
  191. QMessageBox::warning(this,"Service Not Running","Can't connect to the ZeroTier One service. Is it running?",QMessageBox::Ok);
  192. ui->noNetworksLabel->setVisible(true);
  193. ui->noNetworksLabel->setText("Connecting to Service...");
  194. ui->bottomContainerWidget->setVisible(false);
  195. ui->networkListWidget->setVisible(false);
  196. }
  197. zeroTierClient->send("info");
  198. zeroTierClient->send("listnetworks");
  199. zeroTierClient->send("listpeers");
  200. }
  201. void MainWindow::customEvent(QEvent *event)
  202. {
  203. ZTMessageEvent *m = (ZTMessageEvent *)event; // only one custom event type so far
  204. if (m->ztMessage.size() == 0)
  205. return;
  206. this->cyclesSinceResponseFromService = 0;
  207. std::vector<std::string> hdr(ZeroTier::Node::LocalClient::splitLine(m->ztMessage[0]));
  208. if (hdr.size() < 2)
  209. return;
  210. if (hdr[0] != "200")
  211. return;
  212. if (hdr[1] == "info") {
  213. if (hdr.size() >= 3)
  214. this->myAddress = hdr[2].c_str();
  215. if (hdr.size() >= 4)
  216. this->myStatus = hdr[3].c_str();
  217. if (hdr.size() >= 5)
  218. this->myVersion = hdr[4].c_str();
  219. } else if (hdr[1] == "listnetworks") {
  220. std::map< std::string,std::vector<std::string> > newNetworks;
  221. for(unsigned long i=1;i<m->ztMessage.size();++i) {
  222. std::vector<std::string> l(ZeroTier::Node::LocalClient::splitLine(m->ztMessage[i]));
  223. // 200 listnetworks <nwid> <name> <status> <config age> <type> <dev> <ips>
  224. if ((l.size() == 9)&&(l[2].length() == 16))
  225. newNetworks[l[2]] = l;
  226. }
  227. if (newNetworks != networks) {
  228. networks = newNetworks;
  229. for (bool removed=true;removed;) {
  230. removed = false;
  231. for(int r=0;r<ui->networkListWidget->count();++r) {
  232. NetworkWidget *nw = (NetworkWidget *)ui->networkListWidget->itemWidget(ui->networkListWidget->item(r));
  233. if (!networks.count(nw->networkId())) {
  234. ui->networkListWidget->setVisible(false); // HACK to prevent an occasional crash here, discovered through hours of shotgun debugging... :P
  235. delete ui->networkListWidget->takeItem(r);
  236. removed = true;
  237. break;
  238. }
  239. }
  240. }
  241. ui->networkListWidget->setVisible(true);
  242. std::set<std::string> alreadyDisplayed;
  243. for(int r=0;r<ui->networkListWidget->count();++r) {
  244. NetworkWidget *nw = (NetworkWidget *)ui->networkListWidget->itemWidget(ui->networkListWidget->item(r));
  245. if (networks.count(nw->networkId()) > 0) {
  246. alreadyDisplayed.insert(nw->networkId());
  247. std::vector<std::string> &l = networks[nw->networkId()];
  248. nw->setNetworkName(l[3]);
  249. nw->setStatus(l[4],l[5]);
  250. nw->setNetworkType(l[6]);
  251. nw->setNetworkDeviceName(l[7]);
  252. nw->setIps(l[8]);
  253. }
  254. }
  255. for(std::map< std::string,std::vector<std::string> >::iterator nwdata(networks.begin());nwdata!=networks.end();++nwdata) {
  256. if (alreadyDisplayed.count(nwdata->first) == 0) {
  257. std::vector<std::string> &l = nwdata->second;
  258. NetworkWidget *nw = new NetworkWidget((QWidget *)0,nwdata->first);
  259. nw->setNetworkName(l[3]);
  260. nw->setStatus(l[4],l[5]);
  261. nw->setNetworkType(l[6]);
  262. nw->setNetworkDeviceName(l[7]);
  263. nw->setIps(l[8]);
  264. QListWidgetItem *item = new QListWidgetItem();
  265. item->setSizeHint(nw->sizeHint());
  266. ui->networkListWidget->addItem(item);
  267. ui->networkListWidget->setItemWidget(item,nw);
  268. }
  269. }
  270. }
  271. } else if (hdr[1] == "listpeers") {
  272. this->numPeers = 0;
  273. for(unsigned long i=1;i<m->ztMessage.size();++i) {
  274. std::vector<std::string> l(ZeroTier::Node::LocalClient::splitLine(m->ztMessage[i]));
  275. if ((l.size() >= 5)&&((l[3] != "-")||(l[4] != "-")))
  276. ++this->numPeers; // number of direct peers online -- check for active IPv4 and/or IPv6 address
  277. }
  278. }
  279. if (!ui->networkListWidget->count()) {
  280. ui->noNetworksLabel->setText("You Have Not Joined Any Networks");
  281. ui->noNetworksLabel->setVisible(true);
  282. } else ui->noNetworksLabel->setVisible(false);
  283. if (!ui->bottomContainerWidget->isVisible())
  284. ui->bottomContainerWidget->setVisible(true);
  285. if (!ui->networkListWidget->isVisible())
  286. ui->networkListWidget->setVisible(true);
  287. if (this->myAddress.size())
  288. ui->addressButton->setText(this->myAddress);
  289. else ui->addressButton->setText(" ");
  290. QString st(this->myStatus);
  291. st += ", v";
  292. st += this->myVersion;
  293. st += ", ";
  294. st += QString::number(this->numPeers);
  295. st += " direct links to peers";
  296. ui->statusLabel->setText(st);
  297. }
  298. void MainWindow::on_joinNetworkButton_clicked()
  299. {
  300. QString toJoin(ui->networkIdLineEdit->text());
  301. ui->networkIdLineEdit->setText(QString());
  302. if (!zeroTierClient) // sanity check
  303. return;
  304. if (toJoin.size() != 16) {
  305. 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);
  306. return;
  307. }
  308. zeroTierClient->send((QString("join ") + toJoin).toStdString());
  309. }
  310. void MainWindow::on_actionAbout_triggered()
  311. {
  312. AboutWindow *about = new AboutWindow(this);
  313. about->show();
  314. }
  315. void MainWindow::on_networkIdLineEdit_textChanged(const QString &text)
  316. {
  317. QString newText;
  318. for(QString::const_iterator i(text.begin());i!=text.end();++i) {
  319. switch(i->toLatin1()) {
  320. case '0': newText.append('0'); break;
  321. case '1': newText.append('1'); break;
  322. case '2': newText.append('2'); break;
  323. case '3': newText.append('3'); break;
  324. case '4': newText.append('4'); break;
  325. case '5': newText.append('5'); break;
  326. case '6': newText.append('6'); break;
  327. case '7': newText.append('7'); break;
  328. case '8': newText.append('8'); break;
  329. case '9': newText.append('9'); break;
  330. case 'a': newText.append('a'); break;
  331. case 'b': newText.append('b'); break;
  332. case 'c': newText.append('c'); break;
  333. case 'd': newText.append('d'); break;
  334. case 'e': newText.append('e'); break;
  335. case 'f': newText.append('f'); break;
  336. case 'A': newText.append('a'); break;
  337. case 'B': newText.append('b'); break;
  338. case 'C': newText.append('c'); break;
  339. case 'D': newText.append('d'); break;
  340. case 'E': newText.append('e'); break;
  341. case 'F': newText.append('f'); break;
  342. default: break;
  343. }
  344. }
  345. if (newText.size() > 16)
  346. newText.truncate(16);
  347. ui->networkIdLineEdit->setText(newText);
  348. }
  349. void MainWindow::on_addressButton_clicked()
  350. {
  351. QApplication::clipboard()->setText(this->myAddress);
  352. }
  353. void MainWindow::on_actionQuick_Start_triggered()
  354. {
  355. Ui::QuickstartDialog qd;
  356. QDialog *qdd = new QDialog(this);
  357. qd.setupUi(qdd);
  358. qdd->setModal(false);
  359. qdd->show();
  360. }